http://backbonejs.org의 한글 번역본입니다.
번역 : 윤종우

Backbone에 대해 스터디하면서 또, 팀내 세미나를 준비하면서 Backbone framework 관련 문서를 번역해봤다. 영어해석 능력이 떨어지므로 원문은 유지하고 문단별로 하단에 한글번역을 위치해보았다. 나름 재미있고 의미있는 작업이었음 :)

오역에 대한 피드백은 아래로 부탁합니다.
twitter : _wooya
tumblr : http://ryan0822.tumblr.com/

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Backbone.js는 key-value 바인딩 기반의 모델(models)과 사용자 이벤트, 고급 API(열거 가능한 기능)을 제공하는 컬렉션(collections), 선언적 이벤트 처리가 가능한 뷰(views)를 제공함으로써 웹에플리케이션 구조를 제공하고, 이 모든 것을 RESTful JSON 인터페이스를 통하여 당신의 이미 존재하는 API와 연결 할 수 있다.

The project is hosted on GitHub, and the annotated source code is available, as well as an online test suite, an example application, a list of tutorials and a long list of real-world projects that use Backbone. Backbone is available for use under the MIT software license.

이 프로젝트는 GitHub를 통하여 제공하고 있으며, 주석이 달린 소스뿐만아니라 온라인 test suite, 예제 어플리케이션, 튜터리얼, 실제 Backbone을 사용하고 있는 서비스 리스트를 제공한다. Backbone은 MIT 라이센스 아래에 이용가능하다.

You can report bugs and discuss features on the GitHub issues page, on Freenode IRC in the #documentcloud channel, post questions to the Google Group, add pages to the wiki or send tweets to @documentcloud.

당신은 GitHub issues page, Freenode IRC의 #documentcloud 채널, Google Group에서 질문을 작성, wiki에 페이지 추가, @documentcloud로 트윗 발송 등을 통하여 버그를 리포트하고 기능을 토론할 수 있다.

Backbone is an open-source component of DocumentCloud.

Backbone is DocumentCloud의 오픈소스 컴포넌트이다.

Downloads & Dependencies (Right-click, and use "Save As")

Development Version (0.9.2) 52kb, Full source, lots of comments
Production Version (0.9.2) 5.6kb, Packed and gzipped

Backbone's only hard dependency is Underscore.js ( > 1.3.1). For RESTful persistence, history support via Backbone.Router and DOM manipulation with Backbone.View, include json2.js, and either jQuery ( > 1.4.2) or Zepto.

Backbone의 강한 종속성은 오직 Underscore.js ( > 1.3.1)이다. RESTful persistence를 위해, Backbone.Router를 통해 히스토리를 제공하며, DOM 조작은 json2.jsjQuery ( > 1.4.2) 또는 Zepto를 포함한 Backbone.View를 통해 제공한다.

Introduction

When working on a web application that involves a lot of JavaScript, one of the first things you learn is to stop tying your data to the DOM. It's all too easy to create JavaScript applications that end up as tangled piles of jQuery selectors and callbacks, all trying frantically to keep data in sync between the HTML UI, your JavaScript logic, and the database on your server. For rich client-side applications, a more structured approach is often helpful.

많은 Javascript를 포함한 웹 에플리케이션을 작업할 때, 당신에게 가장 우선 배우는 것들 중 하나가 DOM에 데이터를 묶는 것을 중지하는 것이다. JQuery 의 selectors와 callbacks이 얽힌 더미로 끝날 Javascript 어플리케이션을 만드는 것은 매우 쉽다, HTML UI와 Javascript 로직과 서버의 데이터베이스를 동기화 하는 과정에서 데이터를 유지하기 위해 미친듯이 노력해야 한다. 고급 client-side 어플리케이션에서는 좀더 체계적인 접근방식이 종종 도움이 된다.

With Backbone, you represent your data as Models, which can be created, validated, destroyed, and saved to the server. Whenever a UI action causes an attribute of a model to change, the model triggers a "change" event; all the Views that display the model's state can be notified of the change, so that they are able to respond accordingly, re-rendering themselves with the new information. In a finished Backbone app, you don't have to write the glue code that looks into the DOM to find an element with a specific id, and update the HTML manually — when the model changes, the views simply update themselves.

Backbone을 사용하면, 당신의 데이터는 서버에 생성,검증,제거,저장 가능한 모델(Model)로 제공됩니다. 모델(Model)의 속성값에 따라 UI 액션에 일어나야 할 경우, 모델은 "change" 이벤트를 발생한다; 모델(Model)의 상태를 출력하는 뷰(View)들은 변경에 대한 알림을 받을 수 있다. 그래서 뷰(View)들은 새로운 정보를 가지고 자기자신을 재구성한다던지 적절하게 반응할 수 있다. 완성된 Backbone 앱에서 당신은 특정 id를 갖는 요소를 찾기위해 DOM을 살펴보거나 HTML을 수동적으로 갱신하는 glue code를 작성하지 않아도 된다. 모델(Model)이 변경될 때, 뷰(View)들은 간단하게 자기스스로 갱신된다.

If you're new here, and aren't yet quite sure what Backbone is for, start by browsing the list of Backbone-based projects.

만약 당신이 여기가 처음이고 아직 Backbone이 무엇인지 잘 모른다면 list of Backbone-based projects 를 훑어보는 것으로 시작하라.

Many of the examples that follow are runnable. Click the play button to execute them.

대부분의 예제는 실행가능합니다. play 버튼을 클릭하면 실행됩니다.

Upgrading to 0.9

Backbone's 0.9 series should be considered as a release candidate for an upcoming 1.0. Some APIs have changed, and while there is a change log available, and many new features to take advantage of, there are a few specific changes where you'll need to take care:

Backbone.Events

Events is a module that can be mixed in to any object, giving the object the ability to bind and trigger custom named events. Events do not have to be declared before they are bound, and may take passed arguments. For example:

Events는 어떤 object와도 섞일 수 있는 모듈이다, object에게 사용자 정의 이벤트들을 bind와 trigger 가능하도록 해준다. Events는 bind되기전에 선언할 필요가 없고, 전달된 인자가 있을지도 모른다. 예를들어:

var object = {};

_.extend(object, Backbone.Events);

object.on("alert", function(msg) {
  alert("Triggered " + msg);
});

object.trigger("alert", "an event");

For example, to make a handy event dispatcher that can coordinate events among different areas of your application: var dispatcher = _.clone(Backbone.Events)

예를들어, 당신의 애플리케이션의 다른 영역에서 event를 조정할 수 있는 편리한 이벤트 발송자를 만들려면: var dispatcher = _.clone(Backbone.Events)

onobject.on(event, callback, [context])Alias: bind
Bind a callback function to an object. The callback will be invoked whenever the event is fired. If you have a large number of different events on a page, the convention is to use colons to namespace them: "poll:start", or "change:selection". The event string may also be a space-delimited list of several events...

callback 함수를 object에 바인드시키면 callback은 이벤트가 발생할때마다 불려지게 된다. 만약 페이지 내에 각기 다른 많은 수의 이벤트를 가지고 있다면, 네임스페이스를 위해 콜론(:)을 사용하면 된다: "poll:start" 또는 "change:selection". 또한 이벤트 문자는 스페이스를 구분자로 갖는 이벤트의 리스트의 형태일 수도 있다.

book.on("change:title change:author", ...);

To supply a context value for this when the callback is invoked, pass the optional third argument: model.on('change', this.render, this)

callback이 실행될 때 thiscontext값을 제공하기 위해 임의의 3번째 인자를 받을 수 있다: model.on('change', this.render, this)

Callbacks bound to the special "all" event will be triggered when any event occurs, and are passed the name of the event as the first argument. For example, to proxy all events from one object to another:

바인드된 callback들 중 특별히 "all" 이벤트는 어떤 이벤트가 발생하더라도 실행되며, 첫번째 인자로 이벤트의 이름이 넘어간다. 예를들어, object의 모든이벤트를 다른쪽으로 전달하기 위해서는:

proxy.on("all", function(eventName) {
  object.trigger(eventName);
});

offobject.off([event], [callback], [context])Alias: unbind
Remove a previously-bound callback function from an object. If no context is specified, all of the versions of the callback with different contexts will be removed. If no callback is specified, all callbacks for the event will be removed. If no event is specified, all event callbacks on the object will be removed.

object에서 이전에 바인드된 callback 함수를 제거한다. 만약 context가 명시되지 않으면, context에 관계없이 모든 callback 함수가 제거된다. 만약 callback 함수가 명시되지 않으면 해당 event의 모든 callback 함수가 제거되며, event가 명시되지 않으면 object의 모든 이벤트 callback들이 제거된다.

// Removes just the `onChange` callback.
object.off("change", onChange);

// Removes all "change" callbacks.
object.off("change");

// Removes the `onChange` callback for all events.
object.off(null, onChange);

// Removes all callbacks for `context` for all events.
object.off(null, null, context);

// Removes all callbacks on `object`.
object.off();

triggerobject.trigger(event, [*args])
Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.

event또는 공백으로 구분된 event들에 해당되는 callback들을 실행한다. 바로뒤의 인자들은 event의 callback들이 실행될 때 인자로 전달된다.

Backbone.Model

Models are the heart of any JavaScript application, containing the interactive data as well as a large part of the logic surrounding it: conversions, validations, computed properties, and access control. You extend Backbone.Model with your domain-specific methods, and Model provides a basic set of functionality for managing changes.

로직의 큰부분(전환,검증, 속성값 조작, 접근제어) 일 뿐만 아니라 상호적인 데이터 포함하고 있는 모델(Models)은 Javascript 어플리케이션의 중심이다. 당신의 도메인 특화된 메소드들로 Backbone.Model을 확장(extend)하게 되면, 모델(Model)은 changes를 관리하는 기본적인 기능을 제공한다.

The following is a contrived example, but it demonstrates defining a model with a custom method, setting an attribute, and firing an event keyed to changes in that specific attribute. After running this code once, sidebar will be available in your browser's console, so you can play around with it.

아래는 인위적인 예제이다. 그러나 아래의 예제는 사용자 메소드를 가지고 모델을 정의하고 속성을 설정하고, 특정한 속성값이 변경되었을때 이벤트를 발생시키는 것들을 설명한다. 아래의 코드를 한번 실행하면, 당신의 브라우저 console로 sidebar에 접근가능 하고 테스트 할 수 있다.

var Sidebar = Backbone.Model.extend({
  promptColor: function() {
    var cssColor = prompt("Please enter a CSS color:");
    this.set({color: cssColor});
  }
});

window.sidebar = new Sidebar;

sidebar.on('change:color', function(model, color) {
  $('#sidebar').css({background: color});
});

sidebar.set({color: 'white'});

sidebar.promptColor();

extendBackbone.Model.extend(properties, [classProperties])
To create a Model class of your own, you extend Backbone.Model and provide instance properties, as well as optional classProperties to be attached directly to the constructor function.

당신의 Model class를 만들려면, Backbone.Model을 확장(extend)하고, 인스턴트 속성과 옵션인 클래스 속성(classProperties)을 인자로 제공해라. 클래스 속성(classProperties)은 생성자 함수의 property로 추가된다.

extend correctly sets up the prototype chain, so subclasses created with extend can be further extended and subclassed as far as you like.

extend은 정확하게 프로토타입 체인에 엮이게 된다. 그래서 생성된 subclass를 extend하게 되면 당신이 원하는 대로 더욱 더 확장될 것이다.

var Note = Backbone.Model.extend({

  initialize: function() { ... },

  author: function() { ... },

  coordinates: function() { ... },

  allowedToEdit: function(account) {
    return true;
  }

});

var PrivateNote = Note.extend({

  allowedToEdit: function(account) {
    return account.owns(this);
  }

});

Brief aside on super: JavaScript does not provide a simple way to call super — the function of the same name defined higher on the prototype chain. If you override a core function like set, or save, and you want to invoke the parent object's implementation, you'll have to explicitly call it, along these lines:

var Note = Backbone.Model.extend({
  set: function(attributes, options) {
    Backbone.Model.prototype.set.call(this, attributes, options);
    ...
  }
});

constructor / initializenew Model([attributes])
When creating an instance of a model, you can pass in the initial values of the attributes, which will be set on the model. If you define an initialize function, it will be invoked when the model is created.

모델의 인스턴스를 만들때, 당신은 초기 속성값들을 전달 할 수 있다. 이는 모델에 set하는 것과 같다. 만약 당신이 initialize 함수를 정의하였다면, 모델이 생성될때 실행될 것이다.

new Book({
  title: "One Thousand and One Nights",
  author: "Scheherazade"
});

In rare cases, if you're looking to get fancy, you may want to override constructor, which allows you to replace the actual constructor function for your model.

드문 경우지만, 당신이 모델에 깊이 관여한다면, 당신 모델의 생성자 함수를 대체할 수 있는 생성자를 재정의 할 수 있습니다.

getmodel.get(attribute)
Get the current value of an attribute from the model. For example: note.get("title")

모델의 최신 속성값을 얻는다. 예를들어:note.get("title")

setmodel.set(attributes, [options])
Set a hash of attributes (one or many) on the model. If any of the attributes change the models state, a "change" event will be triggered, unless {silent: true} is passed as an option. Change events for specific attributes are also triggered, and you can bind to those as well, for example: change:title, and change:content. You may also pass individual keys and values.

모델에서 속성의 해시값(하나 또는 다수)을 설정한다. 만약 속성들중 어느속성이 모델의 상태를 바꾸게 된다면, "change" 이벤트가 발생하게될 것이다. 그렇지 않길 바란다면 {silent: true} 옵션으로 전달하면 된다. 특정 속성값의 변화에의해 이벤트가 발생하기 원한다면, 다음과 같이 바인드하면 된다:change:title, and change:content. 또한 당신은 한쌍의 키와 값을 전달할 수 있습니다.

note.set({title: "March 20", content: "In his eyes she eclipses..."});

book.set("title", "A Scandal in Bohemia");

If the model has a validate method, it will be validated before the attributes are set, no changes will occur if the validation fails, and set will return false. Otherwise, set returns a reference to the model. You may also pass an error callback in the options, which will be invoked instead of triggering an "error" event, should validation fail. If {silent: true} is passed as an option, the validation is deferred until the next change.

만약 모델이 validate 메소드를 가지 고 있다면, 속성값이 설정되기 이전에 유효성 검증을 하게 될 것이다. 유효성 검증과정이 실패하게되면 아무런 변화가 없으것이며, setfalse를 리턴할 것이다. 그렇지 않으면 set은 모델의 참조를 리턴한다. 또한 당신은 옵션으로 error callback을 전달할 수도 있다, 이는 유효성 검증이 실패했을때 "error" 이벤트를 발생하는 대신 실행되게 된다. 만약 옵션으로 {silent: true}가 전될되면, 유효성 검증은 다음 변경할 때까지 연기된다.

escapemodel.escape(attribute)
Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks.

get과 비슷하지만 모델 속성의 HTML-escaped된 버전을 리턴한다. 만약 모델에 HTML을 data로 삽입하게된다면, escape를 사용하여 변경댕 속성값은 XSS 공격을 방지할 것이다.

var hacker = new Backbone.Model({
  name: "<script>alert('xss')</script>"
});

alert(hacker.escape('name'));

hasmodel.has(attribute)
Returns true if the attribute is set to a non-null or non-undefined value.

해당 속성이 null이 아니거나 속성의 값이 undefined가 아닐 경우 true를 리턴한다.

if (note.has("title")) {
  ...
}

unsetmodel.unset(attribute, [options])
Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.

내부 속성 해시에서 속성을 삭제함으로써 속성을 제거한다. 옵션으로 silent가 전달되지 않으면 "change" 이벤트를 발생시킨다.

clearmodel.clear([options])
Removes all attributes from the model. Fires a "change" event unless silent is passed as an option.

모델의 모든 속성을 제거한다. 옵션으로 silent가 전달되지 않으면 "change" 이벤트를 발생시킨다.

idmodel.id
A special property of models, the id is an arbitrary string (integer id or UUID). If you set the id in the attributes hash, it will be copied onto the model as a direct property. Models can be retrieved by id from collections, and the id is used to generate model URLs by default.

모델의 특별한 속성이다. id는 임의의 문자열이다(정수형 id 또는 UUID). 만약 속성 해시에 id를 설정하면 곧바로 모델의 직접적인 속성으로 복사된다. collection에서 id로 모델을 검색할 수 있고 id는 기본적으로 모델의 URL을 생성하는데 사용된다.

idAttributemodel.idAttribute
A model's unique identifier is stored under the id attribute. If you're directly communicating with a backend (CouchDB, MongoDB) that uses a different unique key, you may set a Model's idAttribute to transparently map from that key to id.

id 속성에 저장될 모델의 유일한 식별자 만약 당신이 직접 다른 유일한 키를 사용하는 backend(CouchDB, MongoDB)와 통신하고자 한다면 모델의 idAttribute를 유일한 키값을 가지는 속성이름으로 지정해야 하며 id로 제공된다.

var Meal = Backbone.Model.extend({
  idAttribute: "_id"
});

var cake = new Meal({ _id: 1, name: "Cake" });
alert("Cake id: " + cake.id);

cidmodel.cid
A special property of models, the cid or client id is a unique identifier automatically assigned to all models when they're first created. Client ids are handy when the model has not yet been saved to the server, and does not yet have its eventual true id, but already needs to be visible in the UI. Client ids take the form: c1, c2, c3 ...

모델의 특별한 속성이다. cid(또는 client id)는 모델이 생성될때 자동으로 할당되는 유일한 식별자이다. Client ids는 아직 서버에 저장되지 않았을때와 id의 값이 정해지지 않았지만 이미 UI에서 보여져야 할때 도움이된다. Client ids의 형태는 다음과 같다: c1, c2, c3 ...

attributesmodel.attributes
The attributes property is the internal hash containing the model's state. Please use set to update the attributes instead of modifying them directly. If you'd like to retrieve and munge a copy of the model's attributes, use toJSON instead.

attributes속성은 모델의 상태를 담고있는 내부 해시이다. attributes 직접 수정하지 말고 set을 이용해라. 만약 모델의 복사본을 가져오기 원한다면 toJSON를 대신 사용해라.

changedmodel.changed
The changed property is the internal hash containing all the attributes that have changed since the last "change" event was triggered. Please do not update changed directly. Its state is maintained internally by set and change. A copy of changed can be acquired from changedAttributes.

changed 속성은 마지막으로 "change"가 발생된 이후 내부 해시의 변화가 있었는지 알려준다. 제발 changed 를 직접 수정하지 마세요. 이것의 상태는 setchange에 의해 내부적으로 관리된다. changed 사본은 changedAttributes에서 얻을 수 있다.

defaultsmodel.defaults or model.defaults()
The defaults hash (or function) can be used to specify the default attributes for your model. When creating an instance of the model, any unspecified attributes will be set to their default value.

defaults 해시(또는 함수)는 당신의 모델의 기본 속성을 지정하는데 사용될 수 있다. 모델의 인스턴스를 생성할때 어떠한 지정되지 않은 속성들은 그것의 기본값으로 설정 될 수 있다.

var Meal = Backbone.Model.extend({
  defaults: {
    "appetizer":  "caesar salad",
    "entree":     "ravioli",
    "dessert":    "cheesecake"
  }
});

alert("Dessert will be " + (new Meal).get('dessert'));

Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances.

자바스크립트에서는 object들은 참조로 제공됨을 기억해라, 그러므로 만약 당신이 기본값으로 object를 포함시켰다면, 그것은 모든 인스턴스간에 공유된다.

toJSONmodel.toJSON()
Return a copy of the model's attributes for JSON stringification. This can be used for persistence, serialization, or for augmentation before being handed off to a view. The name of this method is a bit confusing, as it doesn't actually return a JSON string — but I'm afraid that it's the way that the JavaScript API for JSON.stringify works.

attributes의 복사본을 JSON 형태로 반환된다. 이는 view로 넘겨지기 전에 결과, 직열화, 인자로 사용될 수 있다. 이는 실제로 JSON 문자열을 반환하지 않으므로 이 메소드의 이름이 조금 혼란을 준다. 나는 JavaScript API for JSON.stringify works의 방법에 대해 걱정된다.

var artist = new Backbone.Model({
  firstName: "Wassily",
  lastName: "Kandinsky"
});

artist.set({birthday: "December 16, 1866"});

alert(JSON.stringify(artist));

fetchmodel.fetch([options])
Resets the model's state from the server by delegating to Backbone.sync. Returns a jqXHR. Useful if the model has never been populated with data, or if you'd like to ensure that you have the latest server state. A "change" event will be triggered if the server's state differs from the current attributes. Accepts success and error callbacks in the options hash, which are passed (model, response) as arguments.

Backbone.sync를 통해 서버를 통해 모델의 상태를 재설정한다. jqXHR을 반환한다. 만약 모델이 전혀 데이터로 채워져 있지 않을 경우나 마지막 서버 상태를 보장하기 위해 유용하다. 만약 서버의 상태와 현재 속성이 다르다면 "change" 이벤트가 발생된다. 옵션 해시로 successerror callback을 허용한다. 이때 인자로 (model, response) 가 전달된다.

// Poll every 10 seconds to keep the channel model up-to-date.
setInterval(function() {
  channel.fetch();
}, 10000);

savemodel.save([attributes], [options])
Save a model to your database (or alternative persistence layer), by delegating to Backbone.sync. Returns a jqXHR if validation is successful and false otherwise. The attributes hash (as in set) should contain the attributes you'd like to change — keys that aren't mentioned won't be altered — but, a complete representation of the resource will be sent to the server. As with set, you may pass individual keys and values instead of a hash. If the model has a validate method, and validation fails, the model will not be saved. If the model isNew, the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

모델을 Backbone.sync을 통해 당신의 데이터베이스(또는 대체 퍼시스턴스 계층)에 저장한다. 만약 유효성 검증이 성공하면 jqXHR을 리턴하고, 아니면 false를 리턴한다. attributes 해시(set으로 설정된)가 변경하고 싶은 속성들을 담고 있을 것이다 — 언급되지 않은 키는 변경되지 않는다 — 하지만 리소스의 complete representation이 서버로 전송된다. set과 마찬가지로, 당신은 해시 대신에 키와 값을 전달할 수 있다. 만약 모델이 validate 메소드를 가지고 있고 유효성 검증이 실패한다면, 모벨은 저장되지 않을 것이다. 만약 모델이 isNew이면, "create" (HTTP POST)의 형태로 저장된다, 만약 모델이 이미 서버에 존재한다면, "update" (HTTP PUT)의 형태로 저장된다.

Calling save with new attributes will cause a "change" event immediately, and a "sync" event after the server has acknowledged the successful change. Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model.

새로운 속성값을 가지고 save을 호출하게 되면 "change" 이벤트가 즉시 발생된다. 그리고 서버에 성공적으로 적용되었을때 "sync" 이벤트가 발생한다. 모델의 새로운 속성을 지정하기 전 서버의 응답을 기다릴 경우 {wait: true}를 전달하면 된다.

In the following example, notice how our overridden version of Backbone.sync receives a "create" request the first time the model is saved and an "update" request the second time.

아래의 예제를 보면, 모델의 최초 저장 요청시에는 "create" 요청을 받고, 두번째에는 "update" 요청을 받는 것을 확인할 수 있다.

Backbone.sync = function(method, model) {
  alert(method + ": " + JSON.stringify(model));
  model.id = 1;
};

var book = new Backbone.Model({
  title: "The Rough Riders",
  author: "Theodore Roosevelt"
});

book.save();

book.save({author: "Teddy"});

save accepts success and error callbacks in the options hash, which are passed (model, response) as arguments. The error callback will also be invoked if the model has a validate method, and validation fails. If a server-side validation fails, return a non-200 HTTP response code, along with an error response in text or JSON.

save는 옵션 해시에서 successerror callbacks을 허용하고 인자로 (model, response)를 받는다. error callback은 또한 모델의 validate 메소드에서 유효성 검증 실패시 실행된다. 만약 server-side 유효성 체크 실패시, 200 이 아닌 HTTP 응답코드를 리턴하게 되고, 이때 text또는 JSON으로 응답한다.

book.save("author", "F.D.R.", {error: function(){ ... }});

destroymodel.destroy([options])
Destroys the model on the server by delegating an HTTP DELETE request to Backbone.sync. Returns a jqXHR object, or false if the model isNew. Accepts success and error callbacks in the options hash. Triggers a "destroy" event on the model, which will bubble up through any collections that contain it, and a "sync" event, after the server has successfully acknowledged the model's deletion. Pass {wait: true} if you'd like to wait for the server to respond before removing the model from the collection.

서버의 모델을 제거하기 위해서는 HTTP DELETEBackbone.sync에 요청해라. jqXHR object를 리턴하거나, 모델이 isNew인 경우 false를 리턴한다. 옵션 해시로 successerror callback을 허용한다. 모델에서 "destroy" 이벤트가 발생하면, 모델을 담고 있는 collections들에 이벤트 버블이 발생한다. 그리고 서버의 모델이 성공적으로 삭제되면, "sync"이벤트가 발생한다. 모델의 새로운 속성을 지정하기 전 서버의 응답을 기다릴 경우 {wait: true}를 전달하면 된다.

book.destroy({success: function(model, response) {
  ...
}});

validatemodel.validate(attributes)
This method is left undefined, and you're encouraged to override it with your custom validation logic, if you have any that can be performed in JavaScript. validate is called before set and save, and is passed the model attributes updated with the values from set or save. If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically. If validate returns an error, set and save will not continue, and the model attributes will not be modified. Failed validations trigger an "error" event.

이 메소드는 undefined로 남겨졌다(정의되어 있지 않다). 당신이 임의의 유효성 검증로직으로 override하기를 권장한다. validatesetsave 이전에 호출된다. 만약 속성들이 유효하면 validate에서는 아무것도 리턴하지 않는다; 만약 유효하지 않다면, 선택적으로 에러를 리턴한다. 에러는 화면에 보여지게될 간단한 문자열로 구성된 수도 있고, 완벽한 programmatically하게 설명된 에러 object 일수도 있다. 만약 validate가 error를 리턴할 경우, setsave는 중지되고 모델의 속성은 변경되지 않을 것이다. 실패한 유효성 검증은 "error" 이벤트를 발생한다.

var Chapter = Backbone.Model.extend({
  validate: function(attrs) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

one.on("error", function(model, error) {
  alert(model.get("title") + " " + error);
});

one.set({
  start: 15,
  end:   10
});

"error" events are useful for providing coarse-grained error messages at the model or collection level, but if you have a specific view that can better handle the error, you may override and suppress the event by passing an error callback directly:

"error" 이벤트는 모델과 컬랙션에서 계층적 에러메세지를 제공하는데 유용하다. 그러나 만약 당신이 에러를 처리할 수 있는 더나은 방법이 있다면, error callback을 직접 제공함으로써 이벤트를 override하고 억제할 수 있습니다:

account.set({access: "unlimited"}, {
  error: function(model, error) {
    alert(error);
  }
});

isValidmodel.isValid()
Models may enter an invalid state if you make changes to them silently ... useful when dealing with form input. Call model.isValid() to check if the model is currently in a valid state, according to your validate function.

만약 당신이 모델을 조용하게 변경하였다면 모델은 유효하지 않은 상태일 수도 있다... 폼입력 처리때 유용하다. 현재 모델이 당신의 validate 함수에 의해 유효한 상태인이 알고 싶다면 model.isValid()를 호출해라.

urlmodel.url()
Returns the relative URL where the model's resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.

모델의 리소스가 서버상에 위치할 상대 URL을 리턴한다. 만약 다른곳에 위치한다면, 이 메소드를 알맞은 로직으로 override해라. 일반적인 URL의 형태: "/[collection.url]/[id]" 만약 모델이 컬랙션의 일부가 아니면, "/[urlRoot]/id"

Delegates to Collection#url to generate the URL, so make sure that you have it defined, or a urlRoot property, if all models of this class share a common root URL. A model with an id of 101, stored in a Backbone.Collection with a url of "/documents/7/notes", would have this URL: "/documents/7/notes/101"

Collection#url을 통해 URL을 생성하므로 그것이 정의되어 있는지 확인하거나, 클래스의 모든 모델이 공통의 루트 URL을 공유한다면 urlRoot 속성을 정의해라. 모델이 101의 id값을 가지고 있고, 모델을 가지고 있는 Backbone.Collection"/documents/7/notes"url을 가지고 있을 때 URL은 다음과 같다: "/documents/7/notes/101"

urlRootmodel.urlRoot or model.urlRoot()
Specify a urlRoot if you're using a model outside of a collection, to enable the default url function to generate URLs based on the model id. "/[urlRoot]/id"
Note that urlRoot may also be defined as a function.

모델이 컬랙션 밖에서 사용하려면, urlRoot를 정의하여, 모델 id를 기반으로 URL을 생성함으로서 기본 url함수를 활성화해야 한다. "/[urlRoot]/id" 또한 urlRoot는 함수로도 정희될 수 있다는 것을 주목해라.

var Book = Backbone.Model.extend({urlRoot : '/books'});

var solaris = new Book({id: "1083-lem-solaris"});

alert(solaris.url());

parsemodel.parse(response)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses.

model의 데이터가 fetch, and save시 서버에서 리턴될때마다 parse가 호출된다. 함수의 인자로 원시 response object가 전달되고 모델의 속성 해시에 set되도록 리턴해야 한다. 기본구현은 no-op이며 간단하게 JSON response를 전달한다. 만약 기존에 존재하는 API로 동작 또는 더나은 네임스페이스를 원한다면 override해라.

If you're working with a Rails backend, you'll notice that Rails' default to_json implementation includes a model's attributes under a namespace. To disable this behavior for seamless Backbone integration, set:

만약 서버측을 Rails로 작업한다면, Rails의 기본 to_json가 네임스페이스 아래 모델의 속성이 구현된다는 것을 알수있다. 동일한 Backbone integration을 위해 이 동작을 비활성화시켜라:

ActiveRecord::Base.include_root_in_json = false

clonemodel.clone()
Returns a new instance of the model with identical attributes.

동일한 속성을 가진 모델의 새 인스턴스를 반환한다.

isNewmodel.isNew()
Has this model been saved to the server yet? If the model does not yet have an id, it is considered to be new.

아직 모델을 서버로 저장하지 않았나? 만약 모델이 아직 id를 가지고 있지 않다면, 그것은 new로 간주합니다.

changemodel.change()
Manually trigger the "change" event and a "change:attribute" event for each attribute that has changed. If you've been passing {silent: true} to the set function in order to aggregate rapid changes to a model, you'll want to call model.change() when you're all finished.

각가의 변경된 속성에 대해 수동으로 "change" 이벤트와 "change:attribute" 를 발생한다. 만약 빠른 변경을 위해 the set 함수에 {silent: true}를 전달했다면, 모든 작업이 끝나기 전에 model.change()를 호출해야 한다.

hasChangedmodel.hasChanged([attribute])
Has the model changed since the last "change" event? If an attribute is passed, returns true if that specific attribute has changed.

모델이 이전 "change" 이벤트로부터 변경이 있었는지? 만약 attribute가 전달될때, 속성의 변화가 있으면 true를 리턴한다.

Note that this method, and the following change-related ones, are only useful during the course of a "change" event.

이 메소드 그리고 변경에 관련된 것들은 "change" 이벤트 발생과정 동안에만 유용합니다.

book.on("change", function() {
  if (book.hasChanged("title")) {
    ...
  }
});

changedAttributesmodel.changedAttributes([attributes])
Retrieve a hash of only the model's attributes that have changed. Optionally, an external attributes hash can be passed in, returning the attributes in that hash which differ from the model. This can be used to figure out which portions of a view should be updated, or what calls need to be made to sync the changes to the server.

변경된 속성들만 해시로 리턴한다, 옵션으로 외부 attributes 해시를 전달할 수 있는데, 모델의 해시와 다른속성을 리턴한다. 이는 뷰의 일부를 업데이트하거나, 서버에 변경 내용을 동기화해야 할 지를 알아낸는데 사용될 수 있다.

previousmodel.previous(attribute)
During a "change" event, this method can be used to get the previous value of a changed attribute.

"change"이벤트 발생 동안, 변경된 속성의 이전값을 얻기위해 사용된다.

var bill = new Backbone.Model({
  name: "Bill Smith"
});

bill.on("change:name", function(model, name) {
  alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

previousAttributesmodel.previousAttributes()
Return a copy of the model's previous attributes. Useful for getting a diff between versions of a model, or getting back to a valid state after an error occurs.

모델의 이전 속성들의 복사본을 리턴한다. 모델의 버전사이에 다른점을 얻거나, 에러발생시 다시 유효한 상태로 돌아갈때 유용하다.

Backbone.Collection

Collections are ordered sets of models. You can bind "change" events to be notified when any model in the collection has been modified, listen for "add" and "remove" events, fetch the collection from the server, and use a full suite of Underscore.js methods.

컬랙션은 정렬된 모델들의 집합이다. 컬랙션 안의 어떠한 모델이 수정되더라도 "change"이벤트를 통하여 알 수 있도록 bind할 수 있으며, "add""remove"를 listen하고 서버에서 컬랙션을 fetch하며, Underscore.js methods를 사용할 수 있다.

Any event that is triggered on a model in a collection will also be triggered on the collection directly, for convenience. This allows you to listen for changes to specific attributes in any model in a collection, for example: Documents.on("change:selected", ...)

편리하게, 컬랙션안의 모델에서 발생한 이벤트는 또한 컬렌션에 바로 발생한다. 이는 당신이 컬랙션안의 모델에서 특정한 속성을 listen하게 허용한다, 예를들어: Documents.on("change:selected", ...)

extendBackbone.Collection.extend(properties, [classProperties])
To create a Collection class of your own, extend Backbone.Collection, providing instance properties, as well as optional classProperties to be attached directly to the collection's constructor function.

당신의 컬랙션 클래스를 만들기 위해, Backbone.Collection를 확장하라, 인스턴스 properties뿐만 아니라 선택적으로 classProperties을 직접 컬랙션의 생성자 함수에 첨부할 수 있다.

modelcollection.model
Override this property to specify the model class that the collection contains. If defined, you can pass raw attributes objects (and arrays) to add, create, and reset, and the attributes will be converted into a model of the proper type.

컬렉션에 포함할 특정 모델 클레스를 위해 이 속성을 override해라. 만약 정의되면, 당신은 add, create, 그리고 reset으로 원시 속성 object들(그리고 배열들)을 전달할 수 있다, 그리고 속성들은 적절한 유형의 모델로 변환될 것이다.

var Library = Backbone.Collection.extend({
  model: Book
});

constructor / initializenew Collection([models], [options])
When creating a Collection, you may choose to pass in the initial array of models. The collection's comparator function may be included as an option. If you define an initialize function, it will be invoked when the collection is created.

컬랙션을 만들때, 다신은 models로 구성된 초기 배열을 전달 할 수도 있다. 컬랙션의 comparator 함수는 옵션으로 포함될 수 있다. 만약 당신이 initialize함수를 정의하면, 컬랙션이 생성될 때 실행될 것이다.

var tabs = new TabSet([tab1, tab2, tab3]);

modelscollection.models
Raw access to the JavaScript array of models inside of the collection. Usually you'll want to use get, at, or the Underscore methods to access model objects, but occasionally a direct reference to the array is desired.

컬랙션안의 모델들의 자바스크립트 배열에 직접 접근한다. 일반적으로 모델 objects에 접근하기 위해 get, at, 또는 Underscore methods를 사용하겠지만, 때로는 직접 배열에 접근하는 것도 필요하다.

toJSONcollection.toJSON()
Return an array containing the attributes hash of each model in the collection. This can be used to serialize and persist the collection as a whole. The name of this method is a bit confusing, because it conforms to JavaScript's JSON API.

컬랙션안의 각각의 모델 속성해시를 포함한 배열을 리턴한다. 컬랙션 전체를 직렬화 하거나 persist할 때 사용될 수 있다. 이메소드의 이름은 혼란스러울 수 있지만, JavaScript's JSON API를 준수한다.

var collection = new Backbone.Collection([
  {name: "Tim", age: 5},
  {name: "Ida", age: 26},
  {name: "Rob", age: 55}
]);

alert(JSON.stringify(collection));

Underscore Methods (28)
Backbone proxies to Underscore.js to provide 28 iteration functions on Backbone.Collection. They aren't all documented here, but you can take a look at the Underscore documentation for the full details…

Backbone.CollectionUnderscore.js의 28개 iteration 함수를 제공한다. 그것을은 이곳에 문서화 되어 있지 않지만 자세한 사항을 Underscore 문서에서 확인할 수 있다.

Books.each(function(book) {
  book.publish();
});

var titles = Books.map(function(book) {
  return book.get("title");
});

var publishedBooks = Books.filter(function(book) {
  return book.get("published") === true;
});

var alphabetical = Books.sortBy(function(book) {
  return book.author.get("name").toLowerCase();
});

addcollection.add(models, [options])
Add a model (or an array of models) to the collection. Fires an "add" event, which you can pass {silent: true} to suppress. If a model property is defined, you may also pass raw attributes objects, and have them be vivified as instances of the model. Pass {at: index} to splice the model into the collection at the specified index. Likewise, if you're a callback listening to a collection's "add" event, options.index will tell you the index at which the model is being added to the collection.

모델(또는 모델로 이루어진 배열)을 컬랙션에 추가한다. "add" 이벤트를 발생시키지 않으려면 {silent: true}를 전달해라. 만약 model이 정의되어 있다면, 당신은 또한 원시 속성 objects를 전달할 수 있고 그것들은 모델의 인스턴스로 확인할 수 있다. {at: index}를 전달하면 모델을 지정된 index로 splice 할 수 있다. 마찬가지로 컬랙션의 "add" 이벤트를 listen시 options.index는 컬랙션에 추가된 모델의 index를 알려줄 것이다.

var ships = new Backbone.Collection;

ships.on("add", function(ship) {
  alert("Ahoy " + ship.get("name") + "!");
});

ships.add([
  {name: "Flying Dutchman"},
  {name: "Black Pearl"}
]);

removecollection.remove(models, [options])
Remove a model (or an array of models) from the collection. Fires a "remove" event, which you can use silent to suppress. If you're a callback listening to the "remove" event, the index at which the model is being removed from the collection is available as options.index.

컬랙션에서 모델(또는 모델로 구성된 배열)을 제거한다. "remove" 이벤트를 발생시키지 않으려면 silent를 사용하면 된다. "remove"를 listen하면 모델이 삭제된 index는 options.index로 이용가능하다.

getcollection.get(id)
Get a model from a collection, specified by id.

컬랙션에서 지정된 id의 모델을 얻는다.

var book = Library.get(110);

getByCidcollection.getByCid(cid)
Get a model from a collection, specified by client id. The client id is the .cid property of the model, automatically assigned whenever a model is created. Useful for models which have not yet been saved to the server, and do not yet have true ids.

컬랙션에서 지정된 client id를 가진 모델을 얻는다. client id는 모델이 생성될때 자동 할당되는 모델의 .cid속성이다. 아직 저장되지 않았거나, 아직 id를 가지고 있지 않을때 유용하다.

atcollection.at(index)
Get a model from a collection, specified by index. Useful if your collection is sorted, and if your collection isn't sorted, at will still retrieve models in insertion order.

컬랙션에서 특정 index의 모델을 얻는다. 컬랙션이 정렬되어 있을때 유용하다. 그리고 컬랙션이 정렬되어 있지 않을때는, at은 삽입순서대로 모델을 리턴한다.

pushcollection.push(model, [options])
Add a model at the end of a collection. Takes the same options as add.

컬랙션의 끝에 모델을 추가한다. add와 동일한 옵션을 받는다.

popcollection.pop([options])
Remove and return the last model from a collection. Takes the same options as remove.

컬랙선의 마지막 모델을 리턴하고 제거한다. remove와 동일한 옵션을 받는다.

unshiftcollection.unshift(model, [options])
Add a model at the beginning of a collection. Takes the same options as add.

컬랙션의 맨처음에 모델을 추가한다. add와 동일한 옵션을 받는다.

shiftcollection.shift([options])
Remove and return the first model from a collection. Takes the same options as remove.

컬랙션의 맨처음의 모델을 반환하고 제거한다. remove와 동일한 옵션을 받는다.

lengthcollection.length
Like an array, a Collection maintains a length property, counting the number of models it contains.

배열과 마찬가지로 컬랙션은 컬랙션이 가지고 있는 모델의 갯수를length속성으로 제공한다.

comparatorcollection.comparator
By default there is no comparator function on a collection. If you define a comparator, it will be used to maintain the collection in sorted order. This means that as models are added, they are inserted at the correct index in collection.models. Comparator function can be defined as either a sortBy (pass a function that takes a single argument), or as a sort (pass a comparator function that expects two arguments).

기본적으로, 컬랙션에서 comparator 함수가 없다. 만약 comparator를 정의하면, 정렬순으로 컬랙션을 유지하는데 사용된다. 이는 모델을 추가할때, 모델이 collection.models에 정확한 index에 삽입된다는 것을 의미한다. Comparator 함수는 sortBy(하나의 인자를 전달하는), 또는 sort(두개의 인자를 전달하는) 로 정의될 수 있다.

"sortBy" comparator functions take a model and return a numeric or string value by which the model should be ordered relative to others. "sort" comparator functions take two models, and return -1 if the first model should come before the second, 0 if they are of the same rank and 1 if the first model should come after.

"sortBy" comparator 함수는 하나의 모델을 받아 다른 모델들에 상대적으로 정렬되어야 하는 숫자 또는 문자값을 반환한다. "sort" comparator 함수는 두개의 모델을 받아 첫번째 모델이 앞에 오면 -1, 같으면 0 그리고 첫번째 모델이 뒤에 오면 1 을 리턴한다.

Note how even though all of the chapters in this example are added backwards, they come out in the proper order:

아래예제에서 모든 챕터들이 역으로 추가되지만, 적절한 순서대로 출력되는 것을 주목해라.

var Chapter  = Backbone.Model;
var chapters = new Backbone.Collection;

chapters.comparator = function(chapter) {
  return chapter.get("page");
};

chapters.add(new Chapter({page: 9, title: "The End"}));
chapters.add(new Chapter({page: 5, title: "The Middle"}));
chapters.add(new Chapter({page: 1, title: "The Beginning"}));

alert(chapters.pluck('title'));

Collections with comparator functions will not automatically re-sort if you later change model attributes, so you may wish to call sort after changing model attributes that would affect the order.

comparator함수를 가지고 있는 컬랙션은 모델의 속성이 갱신되더라고 자동으로 재정렬 하지 않을 것이다. 그러므로 모델 속성 변경 후 sort를 호출해야 그제서야 정렬될 것이다.

sortcollection.sort([options])
Force a collection to re-sort itself. You don't need to call this under normal circumstances, as a collection with a comparator function will maintain itself in proper sort order at all times. Calling sort triggers the collection's "reset" event, unless silenced by passing {silent: true}

컬랙션 자체를 다시 정렬하도록 한다. comparator 함수를 가지고 있는 컬랙션은 항상 적절하게 정렬을 하기 때문에 일반적으로는 호출할 필요는 없다. sort 호출 시 컬랙션의 "reset" 이벤트가 발생하며, 이벤트 발생을 원하지 않으면 {silent: true}를 전달해라.

pluckcollection.pluck(attribute)
Pluck an attribute from each model in the collection. Equivalent to calling map, and returning a single attribute from the iterator.

컬랙션안의 각각의 모델에서 속성값을 뽑아낸다. map을 호출하는것과 동일하며, iterator를 통해 하나의 속성을 반환한다.

var stooges = new Backbone.Collection([
  {name: "Curly"},
  {name: "Larry"},
  {name: "Moe"}
]);

var names = stooges.pluck("name");

alert(JSON.stringify(names));

wherecollection.where(attributes)
Return an array of all the models in a collection that match the passed attributes. Useful for simple cases of filter.

전달된 attributes와 일치하는 컬랙션안의 모든 모델들을 배열로 반환한다. 간단한 filter의 경우 유용하다.

var friends = new Backbone.Collection([
  {name: "Athos",      job: "Musketeer"},
  {name: "Porthos",    job: "Musketeer"},
  {name: "Aramis",     job: "Musketeer"},
  {name: "d'Artagnan", job: "Guard"},
]);

var musketeers = friends.where({job: "Musketeer"});

alert(musketeers.length);

urlcollection.url or collection.url()
Set the url property (or function) on a collection to reference its location on the server. Models within the collection will use url to construct URLs of their own.

서버의 컬랙션 위치를 참조하기 위한 url속성(또는 함수)을 설정한다. 컬랙션안의 모델들은 자신의 URL을 만드는데 컬랙션의 url을 사용할 것이다.

var Notes = Backbone.Collection.extend({
  url: '/notes'
});

// Or, something more sophisticated:

var Notes = Backbone.Collection.extend({
  url: function() {
    return this.document.url() + '/notes';
  }
});

parsecollection.parse(response)
parse is called by Backbone whenever a collection's models are returned by the server, in fetch. The function is passed the raw response object, and should return the array of model attributes to be added to the collection. The default implementation is a no-op, simply passing through the JSON response. Override this if you need to work with a preexisting API, or better namespace your responses. Note that afterwards, if your model class already has a parse function, it will be run against each fetched model.

fetch시에 컬랙션의 모델이 서버에서 리턴될 때마다 Backbone에 의해 parse가 호출된다. 함수(parse)는 원시 response object와 컬랙션에 add된 후 반환된 모델 속성들의 배열이 전달된다. 기본구현은 no-op로 간단한 JSON 응답을 전달한다. 기존 API 또는 더나은 네임스페이스가 있다면 이것을 override해라. 모델 클래스에 parse 함수가 있다면 각각의 fetch 모델에 대해 실행된 후 컬랙션의 parse가 실행됨을 유의해라.

var Tweets = Backbone.Collection.extend({
  // The Twitter Search API returns tweets under "results".
  parse: function(response) {
    return response.results;
  }
});

fetchcollection.fetch([options])
Fetch the default set of models for this collection from the server, resetting the collection when they arrive. The options hash takes success and error callbacks which will be passed (collection, response) as arguments. When the model data returns from the server, the collection will reset. Delegates to Backbone.sync under the covers for custom persistence strategies and returns a jqXHR. The server handler for fetch requests should return a JSON array of models.

이 컬랙션의 기본 모델셋을 서버에서 불러오며, 도착시 컬랙션을 리셋한다. options 해시는 (collection, response)를 인자로 가지는 successerror 를 받는다. 모델 데이터가 서버에서 반환될때, 컬랙션은 reset을 호출한다. Backbone.sync를 통해 임의의 persistence 전략을 수행하고 jqXHR를 리턴한다. fetch 요청시 서버 핸들러는 JSON타입의 모델 배열을 리턴해야 한다.

Backbone.sync = function(method, model) {
  alert(method + ": " + model.url);
};

var Accounts = new Backbone.Collection;
Accounts.url = '/accounts';

Accounts.fetch();

If you'd like to add the incoming models to the current collection, instead of replacing the collection's contents, pass {add: true} as an option to fetch.

만약 수신하는 모델을 현재 컬랙션에 추가하고 싶으면, 컬랙션의 내용을 바꿔치기 하는 대신, fetch 시 옵션에 {add: true}를 전달하라.

jQuery.ajax options can also be passed directly as fetch options, so to fetch a specific page of a paginated collection: Documents.fetch({data: {page: 3}})

jQuery.ajax 옵션 또한 직접 fetch 옵션에 전달 할 수 있고, 특정한 페이지로 구분된 컬렉션을 받아오려면 : Documents.fetch({data: {page: 3}})

Note that fetch should not be used to populate collections on page load — all models needed at load time should already be bootstrapped in to place. fetch is intended for lazily-loading models for interfaces that are not needed immediately: for example, documents with collections of notes that may be toggled open and closed.

fetch는 페이지로드시 컬랙션을 생성하기 위해 사용되어서는 안된다는점에 유의해라— 모든 모델은 로드시점에 이미 적절한 곳에 bootstrapped 되어 있어야 한다. fetch는 즉각적으로 필요하지 않는 레이지로딩 모델을 위해 제공되었다: 예를 들어, 열기/닫기 토글이 되는 노트로 구성된 문서

resetcollection.reset(models, [options])
Adding and removing models one at a time is all well and good, but sometimes you have so many models to change that you'd rather just update the collection in bulk. Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end. Pass {silent: true} to suppress the "reset" event. Using reset with no arguments is useful as a way to empty the collection.

한번에 한번씩 모델을 추가하거나 제거하는 것은 좋다. 그러나 때때로 많은 모델을 변경해야 할 때 컬랙션을 한꺼번에 업데이트 해야 할 때도 있다. 새로운 모델(또는 속성 해시)의 리스트로 컬랙션을 대체하지 위해서 reset를 사용해라. 그리고 마지막에 "reset" 이벤트가 발생한다. {silent: true} 를 전달하면 "reset" 이벤트가 발생하는 것을 방지할 수 있다. 인자를 넘기지 않고 "reset"을 호출하는 것은 컬랙션을 비우는 유용한 방법이다.

Here's an example using reset to bootstrap a collection during initial page load, in a Rails application.

아래는 Rails 어플리케이션에서 reset을 사용하여 컬랙션을 bootstrap 하는 예제이다.

<script>
  var Accounts = new Backbone.Collection;
  Accounts.reset(<%= @accounts.to_json %>);
</script>

Calling collection.reset() without passing any models as arguments will empty the entire collection.

어떤 모델이든 인자로 넘기지 않고 collection.reset() 호출하면 컬랙션을 비우게 될것이다.

createcollection.create(attributes, [options])
Convenience to create a new instance of a model within a collection. Equivalent to instantiating a model with a hash of attributes, saving the model to the server, and adding the model to the set after being successfully created. Returns the model, or false if a validation error prevented the model from being created. In order for this to work, you should set the model property of the collection. The create method can accept either an attributes hash or an existing, unsaved model object.

컬랙션 안에서 새로운 모델 인스턴스를 편리하게 생성한다. 속성해시를 가지고 모델을 생성하며, 서버에 모델을 저장하고, 저장 성공 후 모델을 셋에 추가하는 것과 동일하다. 만약 모델생성 중 유효성 검증에 실패하면 false를 리턴, 성공하면 생성된 모델을 리턴한다. 정상적으로 동작하게 하려면, 컬랙션의 모델 속성을 설정해야 한다. create 메소드는 속성해시와 저장되지 않은 모델 모두 인자로 허용한다.

Creating a model will cause an immediate "add" event to be triggered on the collection, as well as a "sync" event, once the model has been successfully created on the server. Pass {wait: true} if you'd like to wait for the server before adding the new model to the collection.

만들어지 모델은 즉각 "add" 이벤트를 컬랙션에 발생시키며, 서버에 성공적으로 저장되면 "sync" 이벤트를 발생시킨다. 만약 컬랙션의 새로운 모델이 서버에 저장되기 전까지 기다리려면 {wait: true}를 전달하면 된다.

var Library = Backbone.Collection.extend({
  model: Book
});

var NYPL = new Library;

var othello = NYPL.create({
  title: "Othello",
  author: "William Shakespeare"
});

Backbone.Router

Web applications often provide linkable, bookmarkable, shareable URLs for important locations in the app. Until recently, hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API, it's now possible to use standard URLs (/page). Backbone.Router provides methods for routing client-side pages, and connecting them to actions and events. For browsers which don't yet support the History API, the Router handles graceful fallback and transparent translation to the fragment version of the URL.

웹 어플리케이션은 링크, 북마크, 공유 할수 있는 URL을 제공한다. 최근까지 hash fragments(#page) 가 퍼머링크를 제공하기 위해 사용되었지만, History API가 생긴 후에는 standard URLs (/page로 사용가능하다. Backbone.Router 클라이언트측의 페이지 라우팅하고, 액션과 이벤트를 연결하는 메소드들을 제공한다. History API 를 지원하지 않는 브라우저에서는 hash fragments 버전의 URL 방식을 제공한다.

During page load, after your application has finished creating all of its routers, be sure to call Backbone.history.start(), or Backbone.history.start({pushState: true}) to route the initial URL.

페이지 로딩시, 모든 라우터 생성을 끝낸뒤에 Backbone.history.start(), 또는 Backbone.history.start({pushState: true})를 호출해서 시작 URL을 라우트할 수 있도록 해라.

extendBackbone.Router.extend(properties, [classProperties])
Get started by creating a custom router class. Define actions that are triggered when certain URL fragments are matched, and provide a routes hash that pairs routes to actions. Note that you'll want to avoid using a leading slash in your route definitions:

커스텀 라우터 클래스를 생성한다. 특정 URL fragment가 일치할때 실행될 액션과, 라우트를 액션으로 연결하는 routes 해시를 정의해라. 라우트 정의 앞부분에 /를 붙이지 않는 것을 주의해라:

var Workspace = Backbone.Router.extend({

  routes: {
    "help":                 "help",    // #help
    "search/:query":        "search",  // #search/kiwis
    "search/:query/p:page": "search"   // #search/kiwis/p7
  },

  help: function() {
    ...
  },

  search: function(query, page) {
    ...
  }

});

routesrouter.routes
The routes hash maps URLs with parameters to functions on your router, similar to the View's events hash. Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components.

라우트 해시는 파라메터를 가지는 URL을 함수로 매핑한다, 이는 Viewevents hash와 유사하다. 라우드는 슬래시 사이의 단일 URL컴퍼넌트와 일치하는 :param 파라메터 부분; 그리고 어떠한 URL컴포넌트와 일치하는 *splatsplat 부분을 가지고 있을 수 있다.

For example, a route of "search/:query/p:page" will match a fragment of #search/obama/p2, passing "obama" and "2" to the action. A route of "file/*path" will match #file/nested/folder/file.txt, passing "nested/folder/file.txt" to the action.

예를 들어, "search/:query/p:page"의 라우드는 #search/obama/p2의 fragment로 매치되고, "obama""2"가 액션으로 전달된다. "file/*path"의 라우트는 #file/nested/folder/file.txt와 매치될것이며, "nested/folder/file.txt"가 액션으로 전달된다.

When the visitor presses the back button, or enters a URL, and a particular route is matched, the name of the action will be fired as an event, so that other objects can listen to the router, and be notified. In the following example, visiting #help/uploading will fire a route:help event from the router.

방문자가 back버튼을 눌렀거나, URL을 입력할때 특정라우터와 일치하면, 액션이름이 event로 실행되어 다른 object들이 listen하여 알게될 수 있다. 아래의 예제에서, #help/uploading를 방문할 때 route:help 이벤트가 라우터에서 발생할 것이다.

routes: {
  "help/:page":         "help",
  "download/*path":     "download",
  "folder/:name":       "openFolder",
  "folder/:name-:mode": "openFolder"
}
router.on("route:help", function(page) {
  ...
});

constructor / initializenew Router([options])
When creating a new router, you may pass its routes hash directly as an option, if you choose. All options will also be passed to your initialize function, if defined.

새로운 라우터를 만들때, 당신은 routes 해시를 바로 옵션으로 전달할 수 있다. 또한 만약 initialize 도 정의하여 옵션으로 전달 할 수 있다.

routerouter.route(route, name, [callback])
Manually create a route for the router, The route argument may be a routing string or regular expression. Each matching capture from the route or regular expression will be passed as an argument to the callback. The name argument will be triggered as a "route:name" event whenever the route is matched. If the callback argument is omitted router[name] will be used instead.

수동으로 라우팅을 생성한다. route의 인자는 routing string또는 정규표현식이 될 수 있다. 라우터또는 정규표현식에서 각각의 매칭는 callback의 인자로서 전달된다. 라우트가 매치될 때마다 name 인자는 "route:name" 이벤트로 발생된다. 만약 callback 인자가 생략되면 router[name]이 대신 사용된다.

initialize: function(options) {

  // Matches #page/10, passing "10"
  this.route("page/:number", "page", function(number){ ... });

  // Matches /117-a/b/c/open, passing "117-a/b/c" to this.open
  this.route(/^(.*?)\/open$/, "open");

},

open: function(id) { ... }

navigaterouter.navigate(fragment, [options])
Whenever you reach a point in your application that you'd like to save as a URL, call navigate in order to update the URL. If you wish to also call the route function, set the trigger option to true. To update the URL without creating an entry in the browser's history, set the replace option to true.

어플리케이션에서 URL로 저장하고 싶은 시점에, URL을 갱신하기위해 navigate를 호출하라. 만약 또한 route 함수를 실행하기 원한다면 trigger 옵션을 true로 설정하면된다. 브라우저 히스토리에 남기지 않으면서 URL을 업데이트 하려면 replacetrue로 설정하라.

openPage: function(pageNumber) {
  this.document.pages.at(pageNumber).open();
  this.navigate("page/" + pageNumber);
}

# Or ...

app.navigate("help/troubleshooting", {trigger: true});

# Or ...

app.navigate("help/troubleshooting", {trigger: true, replace: true});

Backbone.history

History serves as a global router (per frame) to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself — you should use the reference to Backbone.history that will be created for you automatically if you make use of Routers with routes.

Historyhashchange 이벤트 또는 pushState를 조작, 적절한 라우트와 매치하고, callback을 발생하여 전역 router(프레임단위)를 제공한다. 이들 중 하나를 당신이 생성할 필요는 없다. Routersroutes를 이용하려면, 자동으로 생성되어지는 Backbone.history의 레퍼런스를 이용해야 한다.

pushState support exists on a purely opt-in basis in Backbone. Older browsers that don't support pushState will continue to use hash-based URL fragments, and if a hash URL is visited by a pushState-capable browser, it will be transparently upgraded to the true URL. Note that using real URLs requires your web server to be able to correctly render those pages, so back-end changes are required as well. For example, if you have a route of /documents/100, your web server must be able to serve that page, if the browser visits that URL directly. For full search-engine crawlability, it's best to have the server generate the complete HTML for the page ... but if it's a web application, just rendering the same content you would have for the root URL, and filling in the rest with Backbone Views and JavaScript works fine.

pushState 지원은 Backbone에서 순수하게 opt-in 기준으로 존재한다. pushState를 지원하지 않는 이전 브라우저에서는 해시기반의 URL fragment를 사용하며, pushState를 지원하는 브라우서에서 해시 URL을 방문하게 되면, 실제 URL로 변환될 것이다. 실제 URL을 이용하려면 당신의 웹서버가 이러한 페이지들을 적절하게 렌더링해야함을 유의해라. 예를들어, 만약 /documents/100를 라우트할때, 당신의 웹서버는 이 페이지를 제공해야만 한다. 검색엔진 크롤링을 위해 서버가 완벽한 HTML 페이지를 생성하는게 가장 좋겠지만, 웹어플리케이션의 경우, 루트 URL에서와 동일한 컨텐츠를 렌더링하고 Backbone Views와 Javascript로 이어 작성하도록 하자.

startBackbone.history.start([options])
When all of your Routers have been created, and all of the routes are set up properly, call Backbone.history.start() to begin monitoring hashchange events, and dispatching routes.

Routers가 생성되고, 라우트의 모든 속성이 셋업되었을 때, hashchange를 감시하고 라우트를 실행하기 위해 Backbone.history.start()을 호출해라.

To indicate that you'd like to use HTML5 pushState support in your application, use Backbone.history.start({pushState: true}).

당신의 에플리케이션안에서 HTML5의 pushState를 사용하고자 할때, Backbone.history.start({pushState: true}) 같이 사용해라.

If your application is not being served from the root url / of your domain, be sure to tell History where the root really is, as an option: Backbone.history.start({pushState: true, root: "/public/search/"})

만약 어플리케이션이 당신의 도메인의 root url /를 제공하지 못할때, History에게 옵션으로 root가 어디인지 확실히 이야기해라: Backbone.history.start({pushState: true, root: "/public/search/"})

When called, if a route succeeds with a match for the current URL, Backbone.history.start() returns true. If no defined route matches the current URL, it returns false.

호출할 때, 성공적으로 현재 URL과 매치된다면, Backbone.history.start()true를 반환한다. 만약 current URL에 매치되는 라우터가 정의되어 있지 않다면 false를 리턴한다.

If the server has already rendered the entire page, and you don't want the initial route to trigger when starting History, pass silent: true.

만약 서버가 이미 모든 페이지를 랜더링하였고 History시작시에 초기화 라우트를 실행하지 않기 원한다면 silent: true를 전달하라.

Because hash-based history in Internet Explorer relies on an <iframe>, be sure to only call start() after the DOM is ready.

IE브라우저는 <iframe>에 해시기반 히스토리를 의존하기 때문에, DOM 렌더링이 완료된 후에 start()가 호출될 수 있도록 해라.

$(function(){
  new WorkspaceRouter();
  new HelpPaneRouter();
  Backbone.history.start({pushState: true});
});

Backbone.sync

Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request and returns a jqXHR. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.

Backbone.sync는 매번 모델을 서버에 저장하거나 읽을때마다 호출되는 함수이다. 기본적으로 이것은 RESTful JSON 요청하고 jqXHR를 반환하기 위해 (jQuery/Zepto).ajax를 이용한다. 당신은 WebSockets, XML 전송 또는 로컬 저장등을 위한 다른 persistence 전략을 사용하기 위해 override 할 수 있다.

The method signature of Backbone.sync is sync(method, model, [options])

Backbone.sync의 매소드 형태는 sync(method, model, [options])이다.

With the default implementation, when Backbone.sync sends up a request to save a model, its attributes will be passed, serialized as JSON, and sent in the HTTP body with content-type application/json. When returning a JSON response, send down the attributes of the model that have been changed by the server, and need to be updated on the client. When responding to a "read" request from a collection (Collection#fetch), send down an array of model attribute objects.

기본구현에서, Backbone.sync이 모델을 저장하는 요청을 할때, 모델의 속성은 JSON으로 직렬화되어, content-type이 application/json인 HTTP body를 통해 전달된다. JSON응답이 반환될때, 서버에서 모델의 변경된 속성이 보내진다, 그러므로 클라이언트에서 갱신이 필요하다. 컬랙션또는 모델에서 "read" 요청을 할때 모델 속성 object로 이루어진 배열이 서버에서 전달된다.

The sync function may be overriden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.

sync함수는 적역적인 Backbone.sync또는 컬랙션 또는 모델의 sync 함수를 추가함으로 override 가능하다.

The default sync handler maps CRUD to REST like so:

기본 sync 핸들러는 CRUD,REST와 매핑:

As an example, a Rails handler responding to an "update" call from Backbone might look like this: (In real code, never use update_attributes blindly, and always whitelist the attributes you allow to be changed.)

예를들어, Backbone에서 "update" 요청을 받은 Rails 핸들러는 다음과 같다: (실제 코드에서, 절대update_attributes를 바로 사용지 말고 항상 갱신될 속성을 화이트리스트로 관리해라

def update
  account = Account.find params[:id]
  account.update_attributes params
  render :json => account
end

One more tip for Rails integration is to disable the default namespacing for to_json calls on models by setting ActiveRecord::Base.include_root_in_json = false

Rails를 위한 팁을 하나더 말하자면 ActiveRecord::Base.include_root_in_json = false로 설정함으로 to_json에서 기본 네임스페이스를를 위해 사용하지 않도록 하는 것이다.

emulateHTTPBackbone.emulateHTTP = true
If you want to work with a legacy web server that doesn't support Backbones's default REST/HTTP approach, you may choose to turn on Backbone.emulateHTTP. Setting this option will fake PUT and DELETE requests with a HTTP POST, setting the X-HTTP-Method-Override header with the true method. If emulateJSON is also on, the true method will be passed as an additional _method parameter.

만약 Backbone의 기본 REST/HTTP 동작을 지원하지 않는 기존 웹서버로 작업하길 원한다면, 당신은 Backbone.emulateHTTP을 켜는 것을 선택할 수 있다. 이 옵션을 선택함으로서 PUTDELETE 요청은 X-HTTP-Method-Override헤더가 실제 메소드로 설정된 HTTP POST로 변경된다. 또한 emulateJSON을 켜게 되면, 실제 메소드가 추가적으로 _method 메소드로 전달되게 된다.

Backbone.emulateHTTP = true;

model.save();  // POST to "/collection/id", with "_method=PUT" + header.

emulateJSONBackbone.emulateJSON = true
If you're working with a legacy web server that can't handle requests encoded as application/json, setting Backbone.emulateJSON = true; will cause the JSON to be serialized under a model parameter, and the request to be made with a application/x-www-form-urlencoded mime type, as if from an HTML form.

application/json로 인코딩된 요청을 처리하지 못하는 이전 서버에서 작업중이라면, Backbone.emulateJSON = true; 설정하면 JSON은 직렬화되어 model파라메터로 들어가며, 요청은 HTML form 요청인 application/x-www-form-urlencoded mime 형식으로 변경됩니다.

Backbone.View

Backbone views are almost more convention than they are code — they don't determine anything about your HTML or CSS for you, and can be used with any JavaScript templating library. The general idea is to organize your interface into logical views, backed by models, each of which can be updated independently when the model changes, without having to redraw the page. Instead of digging into a JSON object, looking up an element in the DOM, and updating the HTML by hand, you can bind your view's render function to the model's "change" event — and now everywhere that model data is displayed in the UI, it is always immediately up to date.

Backbone 뷰는 코드이기 보다는 컨밴션이다 — 당신의 HTML나 CSS의 어떠한 것도 결정하지 않고, 어떠한 Javascript 탬플릿 라이브러리와 함께 사용할 수 있다. 기본적인 아이디어는 모델이 변경될때 페이지를 다시 그리지 않고 바로 갱신될수 있게 하는 모델의 지원을 받는 논리적인 뷰로 인터페이스를 구정하는 것이다. JSON object를 분석해서, DOM에서 element를 찾고, 손수 HTML를 갱신하는 대신에 당신은 모델의 "change"이벤트레 뷰의 render 함수를 바인드 할 수 있다 — 그래서 모델 데이터가 UI에 출력되는 곳 어디에나 즉시 업데이트 된다.

extendBackbone.View.extend(properties, [classProperties])
Get started with views by creating a custom view class. You'll want to override the render function, specify your declarative events, and perhaps the tagName, className, or id of the View's root element.

사용자 뷰 클래스를 생성한다. 특정 선언된 events, 그리고 아마 tagName, className, 또는 뷰의 루트 element의 id를 위해 override하길 원할 것이다.

var DocumentRow = Backbone.View.extend({

  tagName: "li",

  className: "document-row",

  events: {
    "click .icon":          "open",
    "click .button.edit":   "openEditDialog",
    "click .button.delete": "destroy"
  },

  render: function() {
    ...
  }

});

constructor / initializenew View([options])
When creating a new View, the options you pass are attached to the view as this.options, for future reference. There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes. If the view defines an initialize function, it will be called when the view is first created. If you'd like to create a view that references an element already in the DOM, pass in the element as an option: new View({el: existingElement})

새로운 뷰 생성시, 뷰에 추가될 옵션을 나중에 참조할 수 있도록 this.options으로 전달 할 수 있다. model, collection, 몇몇 특별한 옵션인 el, id, className, tagName 그리고 attributes는 직접적으로 뷰에 첨부된다. initialize를 정의하게되면 뷰가 처음 생성될때 호출된다. 만약 뷰를 이미 DOM에 참조되어 있는 element로 생성하려면 element를 옵션으로 전달하라: new View({el: existingElement})

var doc = Documents.first();

new DocumentRow({
  model: doc,
  id: "document-row-" + doc.id
});

elview.el
All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible. this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

모든 뷰들은 DOM element가 페이지에 삽입되었던 그렇지 않던 항상 DOM element을 가지고 있다(el 속성) 이런식으로, 뷰들은 언제나 랜더링 될 수 있으며, 가능한 최소한의 repaint로 높은 성능으로 UI렌더링하기 위해 한번에 DOM에 추가할 수 있다. this.eltagName, className, id 그리고 attributes가 명시되어 있으면 이 속성을 통해 생성된다. 만약 그렇지 않으면 el는 빈 div로 생성된다.

var ItemView = Backbone.View.extend({
  tagName: 'li'
});

var BodyView = Backbone.View.extend({
  el: 'body'
});

var item = new ItemView();
var body = new BodyView();

alert(item.el + ' ' + body.el);

$elview.$el
A cached jQuery (or Zepto) object for the view's element. A handy reference instead of re-wrapping the DOM element all the time.

뷰의 element를 위한 캐시된 jQuery(또는 Zepto) object를 반환한다. 다시 wrapping 할 필요 없이 항상 쓸 수 있는 편리한 참조기능이다.

view.$el.show();

listView.$el.append(itemView.el);

setElementview.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.

만약 Backbone 뷰를 다른 DOM element로 설정하고 싶다면, setElement를 사용해라. $el 레퍼런스와 뷰의 연결된 event들을 이전 element에서 새로운 것으로 이동한다.

attributesview.attributes
A hash of attributes that will be set as HTML DOM element attributes on the view's el (id, class, data-properties, etc.), or a function that returns such a hash.

뷰의 el에서 HTML DOM element에 셋팅될 attributes 해시(id, class, data-properties, etc.), 또는 이러한 hash를 반환하는 함수

$ (jQuery or Zepto)view.$(selector)
If jQuery or Zepto is included on the page, each view has a $ function that runs queries scoped within the view's element. If you use this scoped jQuery function, you don't have to use model ids as part of your query to pull out specific elements in a list, and can rely much more on HTML class attributes. It's equivalent to running: view.$el.find(selector)

만약 jQuery또는 Zepto가 페이지에 포함되어 있으면, 각각의 뷰는 뷰의 element 스코프 안에서 query를 실행할 수 있는 $ 함수를 가진다. 이를 이용하면, 리스트 안의 특정한 엘리멘트를 가지고 query 해서 모델 id를 사용할 필요가 없고, HTML class attributes를 이용하면 된다. 다음을 실행한 결과와 동일하다: view.$el.find(selector)

ui.Chapter = Backbone.View.extend({
  serialize : function() {
    return {
      title: this.$(".title").text(),
      start: this.$(".start-page").text(),
      end:   this.$(".end-page").text()
    };
  }
});

renderview.render()
The default implementation of render is a no-op. Override this function with your code that renders the view template from model data, and updates this.el with the new HTML. A good convention is to return this at the end of render to enable chained calls.

render의 기본 구현은 no-op. 모델 데이터를 가지고 뷰 템플릿을 렌더링 하는 코드로 override해라, 그리고 새로운 HTML을 가지고 this.el를 갱신해라. 올바른 컨벤션은 체인호출을 가능하도록 render 함수의 끝에 return this를 추가하는 것이다.

var Bookmark = Backbone.View.extend({
  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  }
});

Backbone is agnostic with respect to your preferred method of HTML templating. Your render function could even munge together an HTML string, or use document.createElement to generate a DOM tree. However, we suggest choosing a nice JavaScript templating library. Mustache.js, Haml-js, and Eco are all fine alternatives. Because Underscore.js is already on the page, _.template is available, and is an excellent choice if you've already XSS-sanitized your interpolated data.

Backbone은 당신이 HTML을 템플릿하는 것에 대해 어떤 방법을 선호하는지 알지못한다. render 함수에서 HTML문자열을 더하거나 document.createElement를 이용해 DOM 트리를 생성할 수도 있다. 그러나 우리는 괜찮은 JavaScript templating library를 선택하는 것을 추천한다. Mustache.js, Haml-js, 그리고 Eco 모두 괜찮은 대안이다. Underscore.js가 이미 페이지에 있기때문에 _.template도 사용가능하고 당신의 삽입된 데이터가 이미 XSS-sanitized 하다면 훌륭한 선택이 될 것이다.

Whatever templating strategy you end up with, it's nice if you never have to put strings of HTML in your JavaScript. At DocumentCloud, we use Jammit in order to package up JavaScript templates stored in /app/views as part of our main core.js asset package.

템플릿 전략을 어떻게 하던간데, 당신의 Javascript안에 HTML 문자열을 절대 포함시키지 마라. DocumentCloud에서 우리는 Jammit을 이용해서 core.js의 일부로써 /app/views에 패키징해서 저장했다.

removeview.remove()
Convenience function for removing the view from the DOM. Equivalent to calling $(view.el).remove();

DOM에서 뷰를 제거하기위한 편리 함수. $(view.el).remove();를 호출하는것과 같다.

makeview.make(tagName, [attributes], [content])
Convenience function for creating a DOM element of the given type (tagName), with optional attributes and HTML content. Used internally to create the initial view.el.

주어진 타입(tagName)의 DOM element를 추가적인 attributes 와 HTML 컨텐츠를 가지고 생성하기 위한 편리함수다. 내부적으로 view.el를 초기화 할때 사용된다.

var view = new Backbone.View;

var el = view.make("b", {"class": "bold"}, "Bold! ");

$("#make-demo").append(el);

delegateEventsdelegateEvents([events])
Uses jQuery's delegate function to provide declarative callbacks for DOM events within a view. If an events hash is not passed directly, uses this.events as the source. Events are written in the format {"event selector": "callback"}. The callback may be either the name of a method on the view, or a direct function body. Omitting the selector causes the event to be bound to the view's root element (this.el). By default, delegateEvents is called within the View's constructor for you, so if you have a simple events hash, all of your DOM events will always already be connected, and you will never have to call this function yourself.

뷰안에서 DOM events에 대한 선언된 callback을 제공하기 위해 jQuery의 delegate 함수를 이용한다. 만약 events hash가 바로 전달되지 않았으면 소스에서 this.events로 사용해라. 이벤트는 {"event selector": "callback"}와 같은 포멧으로 쓰여진다. callback은 뷰의 메소드 이름, 또는 함수 자체가 될 수 있다. selector를 생략하면 이벤트는 root element (this.el)에 바인드 된다. 기본적으로, delegateEvents는 당신을 위해 뷰의 생성자안에서 호출된다, 그러므로 만약 당신이 간단한 events 해시를 가지고 있으면 모든 DOM 이벤트는 이미 항상 연결되어 있으니, 이함수 자체를 절대 호출할 필요 없다.

The events property may also be defined as a function that returns an events hash, to make it easier to programmatically define your events, as well as inherit them from parent views.

또한 events 속성은 부모뷰에서 상속을 받거나, 좀더 쉽게 프로그래밍적으로 당신의 events를 정의하기 위해 hash를 반환하는 함수로 정의될 수도 있다.

Using delegateEvents provides a number of advantages over manually using jQuery to bind events to child elements during render. All attached callbacks are bound to the view before being handed off to jQuery, so when the callbacks are invoked, this continues to refer to the view object. When delegateEvents is run again, perhaps with a different events hash, all callbacks are removed and delegated afresh — useful for views which need to behave differently when in different modes.

delegateEvents를 이용하면 직접 jQuery를 사용하여 render 과정 중에 이벤트와 자식 element를 바인드 하는 것에 비해 몇가지 장점이 있다. 모든 callback들이 실행될때 뷰에 바인딩된 모든 callback들은 jQuery에 넘겨질 수있기때문에 계속해서 this는 뷰 object를 참조한다. delegateEvents가 다시 실행될 때, 아마 다른 events 해시와 모든 callback은 제거되고 새로 위임될 것이다. — 뷰가 다른 모델에서 다르게 동작해야할 때 유용하다.

A view that displays a document in a search result might look something like this:

아래와 같은 검색결과를 가지고 화면을 출력해야 할때:

var DocumentView = Backbone.View.extend({

  events: {
    "dblclick"                : "open",
    "click .icon.doc"         : "select",
    "contextmenu .icon.doc"   : "showMenu",
    "click .show_notes"       : "toggleNotes",
    "click .title .lock"      : "editAccessLevel",
    "mouseover .title .date"  : "showTooltip"
  },

  render: function() {
    $(this.el).html(this.template(this.model.toJSON()));
    return this;
  },

  open: function() {
    window.open(this.model.get("viewer_url"));
  },

  select: function() {
    this.model.set({selected: true});
  },

  ...

});

undelegateEventsundelegateEvents()
Removes all of the view's delegated events. Useful if you want to disable or remove a view from the DOM temporarily.

모든 뷰의 연결된 이벤트를 제거한다. 뷰를 비활성화 시키거나 DOM에서 임시로 뷰를 제거할 때 유용하다.

Utility Functions

noConflictvar backbone = Backbone.noConflict();
Returns the Backbone object back to its original value. You can use the return value of Backbone.noConflict() to keep a local reference to Backbone. Useful for embedding Backbone on third-party websites, where you don't want to clobber the existing Backbone.

원본 값을 가진 Backbone object를 리턴한다. Backbone의 로컬 레퍼런스를 유지하기 위해 Backbone.noConflict()의 리턴값을 이용할 수도 있다. 서드파티 웹사이트에서 기존의 Backbone과 충돌하지 않도록 할 때 유용하다.

var localBackbone = Backbone.noConflict();
var model = localBackbone.Model.extend(...);

setDomLibraryBackbone.setDomLibrary(jQueryNew);
If you have multiple copies of jQuery on the page, or simply want to tell Backbone to use a particular object as its DOM / Ajax library, this is the function for you.

만약 페이지 안에 여러개의 jQuery가 존재하거나, Backbone이 DOM / Ajax 라이브러리도 특정 object를 사용하길 원할때, 이 함수는 당신을 위한 것이다.

Examples

The list of examples that follows, while long, is not exhaustive. If you've worked on an app that uses Backbone, please add it to the wiki page of Backbone apps.

Jérôme Gravel-Niquet has contributed a Todo List application that is bundled in the repository as Backbone example. If you're wondering where to get started with Backbone in general, take a moment to read through the annotated source. The app uses a LocalStorage adapter to transparently save all of your todos within your browser, instead of sending them to a server. Jérôme also has a version hosted at localtodos.com that uses a MooTools-backed version of Backbone instead of jQuery.

Todos

DocumentCloud

The DocumentCloud workspace is built on Backbone.js, with Documents, Projects, Notes, and Accounts all as Backbone models and collections. If you're interested in history — both Underscore.js and Backbone.js were originally extracted from the DocumentCloud codebase, and packaged into standalone JS libraries.

DocumentCloud Workspace

Rdio

New Rdio was developed from the ground up with a component based framework based on Backbone.js. Every component on the screen is dynamically loaded and rendered, with data provided by the Rdio API. When changes are pushed, every component can update itself without reloading the page or interrupting the user's music. All of this relies on Backbone's views and models, and all URL routing is handled by Backbone's Router. When data changes are signaled in realtime, Backbone's Events notify the interested components in the data changes. Backbone forms the core of the new, dynamic, realtime Rdio web and desktop applications.

Rdio

LinkedIn Mobile

LinkedIn used Backbone.js to create its next-generation HTML5 mobile web app. Backbone made it easy to keep the app modular, organized and extensible so that it was possible to program the complexities of LinkedIn's user experience. The app also uses Zepto, Underscore.js, SASS, iScroll, HTML5 LocalStorage and Canvas. The tech team blogged about their experiences using LocalStorage to improve mobile performance.

LinkedIn Mobile

Flow

MetaLab used Backbone.js to create Flow, a task management app for teams. The workspace relies on Backbone.js to construct task views, activities, accounts, folders, projects, and tags. You can see the internals under window.Flow.

Flow

WordPress.com

WordPress.com is the software-as-a-service version of WordPress. It uses Backbone.js Models, Collections, and Views in its Notifications system. Backbone.js was selected because it was easy to fit into the structure of the application, not the other way around. Automattic (the company behind WordPress.com) is integrating Backbone.js into the Stats tab and other features throughout the homepage.

WordPress.com Notifications

Foursquare

Foursquare is a fun little startup that helps you meet up with friends, discover new places, and save money. Backbone Models are heavily used in the core JavaScript API layer and Views power many popular features like the homepage map and lists.

Foursquare

Wunderkit

Wunderkit is a productivity and social collaboration platform. It uses Backbone.js as the foundation for the single-page application, which is backed by a RESTful Rails API. The freedom and agility that Backbone gives to developers made it possible to build Wunderkit in a very short time and extend it with custom features: a write-through cache using HTML5 localStorage, and a view hierarchy extension to easily manage trees of sub-views. Aside from Backbone, Wunderkit also depends on jQuery, Underscore, Require.js, LESS and doT.js templates.

Wunderkit

Disqus

Disqus chose Backbone.js to power the latest version of their commenting widget. Backbone’s small footprint and easy extensibility made it the right choice for Disqus’ distributed web application, which is hosted entirely inside an iframe and served on thousands of large web properties, including IGN, Wired, CNN, MLB, and more.

Disqus

Khan Academy

Khan Academy is on a mission to provide a free world-class education to anyone anywhere. With thousands of videos, hundreds of JavaScript-driven exercises, and big plans for the future, Khan Academy uses Backbone to keep frontend code modular and organized. User profiles and goal setting are implemented with Backbone, jQuery and Handlebars, and most new feature work is being pushed to the client side, greatly increasing the quality of the API.

Khan Academy

Do

Do is a social productivity app that makes it easy to work on tasks, track projects, and take notes with your team. The Do.com web application was built from the ground up to work seamlessly on your smartphone, tablet and computer. The team used Backbone, CoffeeScript and Handlebars to build a full-featured app in record time and rolled their own extensions for complex navigation and model sync support.

Do

Pitchfork

Pitchfork uses Backbone.js to power its site-wide audio player, Pitchfork.tv, location routing, a write-thru page fragment cache, and more. Backbone.js (and Underscore.js) helps the team create clean and modular components, move very quickly, and focus on the site, not the spaghetti.

Pitchfork

Spin

Spin pulls in the latest news stories from their internal API onto their site using Backbone models and collections, and a custom sync method. Because the music should never stop playing, even as you click through to different "pages", Spin uses a Backbone router for navigation within the site.

Spin

Walmart Mobile

Walmart used Backbone.js to create the new version of their mobile web application and created two new frameworks in the process. Thorax provides mixins, inheritable events, as well as model and collection view bindings that integrate directly with Handlebars templates. Lumbar allows the application to be split into modules which can be loaded on demand, and creates platform specific builds for the portions of the web application that are embedded in Walmart's native Android and iOS applications.

Walmart Mobile

Groupon Now!

Groupon Now! helps you find local deals that you can buy and use right now. When first developing the product, the team decided it would be AJAX heavy with smooth transitions between sections instead of full refreshes, but still needed to be fully linkable and shareable. Despite never having used Backbone before, the learning curve was incredibly quick — a prototype was hacked out in an afternoon, and the team was able to ship the product in two weeks. Because the source is minimal and understandable, it was easy to add several Backbone extensions for Groupon Now!: changing the router to handle URLs with querystring parameters, and adding a simple in-memory store for caching repeated requests for the same data.

Groupon Now!

Basecamp Mobile

37Signals used Backbone.js to create Basecamp Mobile, the mobile version of their popular project management software. You can access all your Basecamp projects, post new messages, and comment on milestones (all represented internally as Backbone.js models).

Basecamp Mobile

Slavery Footprint

Slavery Footprint allows consumers to visualize how their consumption habits are connected to modern-day slavery and provides them with an opportunity to have a deeper conversation with the companies that manufacture the goods they purchased. Based in Oakland, California, the Slavery Footprint team works to engage individuals, groups, and businesses to build awareness for and create deployable action against forced labor, human trafficking, and modern-day slavery through online tools, as well as off-line community education and mobilization programs.

Slavery Footprint

Stripe

Stripe provides an API for accepting credit cards on the web. Stripe's management interface was recently rewritten from scratch in Coffeescript using Backbone.js as the primary framework, Eco for templates, Sass for stylesheets, and Stitch to package everything together as CommonJS modulas. The new app uses Stripe's API directly for the majority of its actions; Backbone.js models made it simple to map client-side models to their corresponding RESTful resources.

Stripe

Airbnb

Airbnb uses Backbone in many of its products. It started with Airbnb Mobile Web (built in six weeks by a team of three) and has since grown to Wish Lists, Match, Search, Communities, Payments, and Internal Tools.

Airbnb

Diaspora

Diaspora is a distributed social network, formed from a number of independently operated pods. You own your personal data, and control with whom you share. All of Diaspora is open-source code, built with Rails and Backbone.js.

Diaspora

SoundCloud Mobile

SoundCloud is the leading sound sharing platform on the internet, and Backbone.js provides the foundation for SoundCloud Mobile. The project uses the public SoundCloud API as a data source (channeled through a nginx proxy), jQuery templates for the rendering, Qunit and PhantomJS for the testing suite. The JS code, templates and CSS are built for the production deployment with various Node.js tools like ready.js, Jake, jsdom. The Backbone.History was modified to support the HTML5 history.pushState. Backbone.sync was extended with an additional SessionStorage based cache layer.

SoundCloud

Art.sy

Art.sy is a place to discover art you'll love. Art.sy is built on Rails, using Grape to serve a robust JSON API. The main site is a single page app written in Coffeescript and uses Backbone to provide structure around this API. An admin panel and partner CMS have also been extracted into their own API-consuming Backbone projects.

Art.sy

Pandora

When Pandora redesigned their site in HTML5, they chose Backbone.js to help manage the user interface and interactions. For example, there's a model that represents the "currently playing track", and multiple views that automatically update when the current track changes. The station list is a collection, so that when stations are added or changed, the UI stays up to date.

Pandora

Inkling

Inkling is a truly cross-platform way to publish interactive learning content.
Inkling for Web uses Backbone.js to make hundreds of complex books — from textbooks to travel guides — more engaging on the web. Beyond your average EPUB eReader, Inkling supports WebGL-enabled 3D graphics, interactive assessments, seamless social sharing, and even a music player, all within a single page Backbone-driven app. Early on, the team decided to keep the site lightweight by using only Backbone.js and raw JavaScript. The result? Complete source code weighing in at a mere 350kb with feature-parity across the iPad, iPhone and web clients. The free chapter in every book makes it easy for anyone to try it out and take a look.

Inkling

Code School

Code School courses teach people about various programming topics like CoffeeScript, CSS, Ruby on Rails, and more. The new Code School course challenge page is built from the ground up on Backbone.js, using everything it has to offer: the router, collections, models, and complex event handling. Before, the page was a mess of jQuery DOM manipulation and manual Ajax calls. Backbone.js helped introduce a new way to think about developing an organized front-end application in Javascript.

Code School

CloudApp

CloudApp is simple file and link sharing for the Mac. Backbone.js powers the web tools which consume the documented API to manage Drops. Data is either pulled manually or pushed by Pusher and fed to Mustache templates for rendering. Check out the annotated source code to see the magic.

CloudApp

SeatGeek

SeatGeek's stadium ticket maps were originally developed with Prototype.js. Moving to Backbone.js and jQuery helped organize a lot of the UI code, and the increased structure has made adding features a lot easier. SeatGeek is also in the process of building a mobile interface that will be Backbone.js from top to bottom.

SeatGeek

Easel

Easel is an in-browser, high fidelity web design tool that integrates with your design and development process. The Easel team uses CoffeeScript, Underscore.js and Backbone.js for their rich visual editor as well as other management functions throughout the site. The structure of Backbone allowed the team to break the complex problem of building a visual editor into manageable components and still move quickly.

Easel

Prose

Prose is a content editor for GitHub, optimized for managing websites built with Jekyll and Github Pages. Prose is itself implemented as a static Jekyll site, using Backbone.js to render the views and handle the routes, as well as Github.js, a small data abstraction layer for manipulating files directly on Github. Read more in the official introduction post, or take a look at the source code.

Prose

Grove.io

Grove.io provides hosted IRC for teams. Backbone.js powers Grove's web client together with Handlebars.js templating. Updates to chat stream are pulled in realtime using long-polling.

Grove.io

KANO/GAMES

KANO/APPS used Backbone.js to create KANO/GAMES, a social gaming website. KANO/GAMES relies on Backbone.js for almost every aspect of the site: for seamless page loading, to construct menus, game listings and game canvases, to build interactive HTML5 avatars, and for user and developer profiles, and live feeds.

KANO/GAMES

Shortmail

410 Labs uses Backbone.js at Shortmail.com to build a fast and responsive inbox, driven by the Router. Backbone works with a Rails backend to provide inbox rendering, archiving, replying, composing, and even a changes feed. Using Backbone's event-driven model and pushing the rendering and interaction logic to the front-end has not only simplified the view code, it has also drastically reduced the load on Shortmail's servers.

Shortmail

scroll kit

scroll kit is a new kind of website builder that makes designing a web page feel more like drawing. The workspace is a single-page web application built with Rails and Backbone.js. In scroll kit, every DOM element is associated with a Backbone model, so that style changes that are made to an element automatically update the model and propagate the change across all its views. Try it out.

scroll kit

Battlefield Play4Free

Battlefield Play4Free is the latest free-to-play first person shooter from the same team that created Battlefield Heroes. The in-game HTML5 front-end for makes heavy use of Backbone's views, models and collections to help keep the code modular and structured.

Battlefield Play4Free

Salon.io

Salon.io provides a space where photographers, artists and designers freely arrange their visual art on virtual walls. Salon.io runs on Rails, but does not use much of the traditional stack, as the entire frontend is designed as a single page web app, using Backbone.js and CoffeeScript.

Salon.io

TileMill

Our fellow Knight Foundation News Challenge winners, MapBox, created an open-source map design studio with Backbone.js: TileMill. TileMill lets you manage map layers based on shapefiles and rasters, and edit their appearance directly in the browser with the Carto styling language. Note that the gorgeous MapBox homepage is also a Backbone.js app.

TileMill

Blossom

Blossom is a lightweight project management tool for lean teams. Backbone.js is heavily used in combination with CoffeeScript to provide a smooth interaction experience. The RESTful backend is built with Flask on Google App Engine.

Blossom

Decide

Decide.com helps people decide when to buy consumer electronics. It relies heavily on Backbone.js to render and update its Search Results Page. An "infinite scroll" feature takes advantage of a SearchResults model containing a collection of Product models to fetch more results and render them on the fly with Mustache. A SearchController keeps everything in sync and maintains page state in the URL. Backbone also powers the user accounts and settings management.

Decide

Trello

Trello is a collaboration tool that organizes your projects into boards. A Trello board holds many lists of cards, which can contain checklists, files and conversations, and may be voted on and organized with labels. Updates on the board happen in real time. The site was built ground up using Backbone.js for all the models, views, and routes.

Trello

Ducksboard

Ducksboard is an online dashboard for your SaaS and business metrics, built with Twisted and Django and using WebSockets. It can fetch data from popular providers or accept input through a simple API. Backbone is used throughout Ducksboard's interface, every widget, dashboard and SaaS account is a Backbone model with several views (data display, configuration view). A live demo is available.

Ducksboard

QuietWrite

James Yu used Backbone.js to create QuietWrite, an app that gives writers a clean and quiet interface to concentrate on the text itself. The editor relies on Backbone to persist document data to the server. He followed up with a Backbone.js + Rails tutorial that describes how to implement CloudEdit, a simple document editing app.

QuietWrite

Tzigla

Cristi Balan and Irina Dumitrascu created Tzigla, a collaborative drawing application where artists make tiles that connect to each other to create surreal drawings. Backbone models help organize the code, routers provide bookmarkable deep links, and the views are rendered with haml.js and Zepto. Tzigla is written in Ruby (Rails) on the backend, and CoffeeScript on the frontend, with Jammit prepackaging the static assets.

Tzigla

F.A.Q.

Catalog of Events
Here's a list of all of the built-in events that Backbone.js can fire. You're also free to trigger your own events on Models and Views as you see fit.

There's More Than One Way To Do It
It's common for folks just getting started to treat the examples listed on this page as some sort of gospel truth. In fact, Backbone.js is intended to be fairly agnostic about many common patterns in client-side code. For example...

References between Models and Views can be handled several ways. Some people like to have direct pointers, where views correspond 1:1 with models (model.view and view.model). Others prefer to have intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy. Others still prefer the evented approach, and always fire events instead of calling methods directly. All of these styles work well.

Batch operations on Models are common, but often best handled differently depending on your server-side setup. Some folks don't mind making individual Ajax requests. Others create explicit resources for RESTful batch operations: /notes/batch/destroy?ids=1,2,3,4. Others tunnel REST over JSON, with the creation of "changeset" requests:

  {
    "create":  [array of models to create]
    "update":  [array of models to update]
    "destroy": [array of model ids to destroy]
  }

Feel free to define your own events. Backbone.Events is designed so that you can mix it in to any JavaScript object or prototype. Since you can use any string as an event, it's often handy to bind and trigger your own custom events: model.on("selected:true") or model.on("editing")

Render the UI as you see fit. Backbone is agnostic as to whether you use Underscore templates, Mustache.js, direct DOM manipulation, server-side rendered snippets of HTML, or jQuery UI in your render function. Sometimes you'll create a view for each model ... sometimes you'll have a view that renders thousands of models at once, in a tight loop. Both can be appropriate in the same app, depending on the quantity of data involved, and the complexity of the UI.

Nested Models & Collections
It's common to nest collections inside of models with Backbone. For example, consider a Mailbox model that contains many Message models. One nice pattern for handling this is have a this.messages collection for each mailbox, enabling the lazy-loading of messages, when the mailbox is first opened ... perhaps with MessageList views listening for "add" and "remove" events.

var Mailbox = Backbone.Model.extend({

  initialize: function() {
    this.messages = new Messages;
    this.messages.url = '/mailbox/' + this.id + '/messages';
    this.messages.on("reset", this.updateCounts);
  },

  ...

});

var Inbox = new Mailbox;

// And then, when the Inbox is opened:

Inbox.messages.fetch();

If you're looking for something more opinionated, there are a number of Backbone plugins that add sophisticated associations among models, available on the wiki.

Backbone doesn't include direct support for nested models and collections or "has many" associations because there are a number of good patterns for modeling structured data on the client side, and Backbone should provide the foundation for implementing any of them. You may want to…

Loading Bootstrapped Models
When your app first loads, it's common to have a set of initial models that you know you're going to need, in order to render the page. Instead of firing an extra AJAX request to fetch them, a nicer pattern is to have their data already bootstrapped into the page. You can then use reset to populate your collections with the initial data. At DocumentCloud, in the ERB template for the workspace, we do something along these lines:

<script>
  var Accounts = new Backbone.Collection;
  Accounts.reset(<%= @accounts.to_json %>);
  var Projects = new Backbone.Collection;
  Projects.reset(<%= @projects.to_json(:collaborators => true) %>);
</script>

You have to escape </ within the JSON string, to prevent javascript injection attacks.

Extending Backbone
Many JavaScript libraries are meant to be insular and self-enclosed, where you interact with them by calling their public API, but never peek inside at the guts. Backbone.js is not that kind of library.

Because it serves as a foundation for your application, you're meant to extend and enhance it in the ways you see fit — the entire source code is annotated to make this easier for you. You'll find that there's very little there apart from core functions, and most of those can be overriden or augmented should you find the need. If you catch yourself adding methods to Backbone.Model.prototype, or creating your own base subclass, don't worry — that's how things are supposed to work.

How does Backbone relate to "traditional" MVC?
Different implementations of the Model-View-Controller pattern tend to disagree about the definition of a controller. If it helps any, in Backbone, the View class can also be thought of as a kind of controller, dispatching events that originate from the UI, with the HTML template serving as the true view. We call it a View because it represents a logical chunk of UI, responsible for the contents of a single DOM element.

Comparing the overall structure of Backbone to a server-side MVC framework like Rails, the pieces line up like so:

Binding "this"
Perhaps the single most common JavaScript "gotcha" is the fact that when you pass a function as a callback, its value for this is lost. With Backbone, when dealing with events and callbacks, you'll often find it useful to rely on _.bind and _.bindAll from Underscore.js.

When binding callbacks to Backbone events, you can choose to pass an optional third argument to specify the this that will be used when the callback is later invoked:

var MessageList = Backbone.View.extend({

  initialize: function() {
    var messages = this.collection;
    messages.on("reset", this.render, this);
    messages.on("add", this.addMessage, this);
    messages.on("remove", this.removeMessage, this);
  }

});

// Later, in the app...

Inbox.messages.add(newMessage);

Working with Rails
Backbone.js was originally extracted from a Rails application; getting your client-side (Backbone) Models to sync correctly with your server-side (Rails) Models is painless, but there are still a few things to be aware of.

By default, Rails adds an extra layer of wrapping around the JSON representation of models. You can disable this wrapping by setting:

ActiveRecord::Base.include_root_in_json = false

... in your configuration. Otherwise, override parse to pull model attributes out of the wrapper. Similarly, Backbone PUTs and POSTs direct JSON representations of models, where by default Rails expects namespaced attributes. You can have your controllers filter attributes directly from params, or you can override toJSON in Backbone to add the extra wrapping Rails expects.

Change Log

0.9.2March 21, 2012Diff
0.9.1Feb. 2, 2012Diff
0.9.0Jan. 30, 2012Diff

0.5.3August 9, 2011
A View's events property may now be defined as a function, as well as an object literal, making it easier to programmatically define and inherit events. groupBy is now proxied from Underscore as a method on Collections. If the server has already rendered everything on page load, pass Backbone.history.start({silent: true}) to prevent the initial route from triggering. Bugfix for pushState with encoded URLs.

0.5.2July 26, 2011
The bind function, can now take an optional third argument, to specify the this of the callback function. Multiple models with the same id are now allowed in a collection. Fixed a bug where calling .fetch(jQueryOptions) could cause an incorrect URL to be serialized. Fixed a brief extra route fire before redirect, when degrading from pushState.

0.5.1July 5, 2011
Cleanups from the 0.5.0 release, to wit: improved transparent upgrades from hash-based URLs to pushState, and vice-versa. Fixed inconsistency with non-modified attributes being passed to Model#initialize. Reverted a 0.5.0 change that would strip leading hashbangs from routes. Added contains as an alias for includes.

0.5.0July 1, 2011
A large number of tiny tweaks and micro bugfixes, best viewed by looking at the commit diff. HTML5 pushState support, enabled by opting-in with: Backbone.history.start({pushState: true}). Controller was renamed to Router, for clarity. Collection#refresh was renamed to Collection#reset to emphasize its ability to both reset the collection with new models, as well as empty out the collection when used with no parameters. saveLocation was replaced with navigate. RESTful persistence methods (save, fetch, etc.) now return the jQuery deferred object for further success/error chaining and general convenience. Improved XSS escaping for Model#escape. Added a urlRoot option to allow specifying RESTful urls without the use of a collection. An error is thrown if Backbone.history.start is called multiple times. Collection#create now validates before initializing the new model. view.el can now be a jQuery string lookup. Backbone Views can now also take an attributes parameter. Model#defaults can now be a function as well as a literal attributes object.

0.3.3Dec 1, 2010
Backbone.js now supports Zepto, alongside jQuery, as a framework for DOM manipulation and Ajax support. Implemented Model#escape, to efficiently handle attributes intended for HTML interpolation. When trying to persist a model, failed requests will now trigger an "error" event. The ubiquitous options argument is now passed as the final argument to all "change" events.

0.3.2Nov 23, 2010
Bugfix for IE7 + iframe-based "hashchange" events. sync may now be overridden on a per-model, or per-collection basis. Fixed recursion error when calling save with no changed attributes, within a "change" event.

0.3.1Nov 15, 2010
All "add" and "remove" events are now sent through the model, so that views can listen for them without having to know about the collection. Added a remove method to Backbone.View. toJSON is no longer called at all for 'read' and 'delete' requests. Backbone routes are now able to load empty URL fragments.

0.3.0Nov 9, 2010
Backbone now has Controllers and History, for doing client-side routing based on URL fragments. Added emulateHTTP to provide support for legacy servers that don't do PUT and DELETE. Added emulateJSON for servers that can't accept application/json encoded requests. Added Model#clear, which removes all attributes from a model. All Backbone classes may now be seamlessly inherited by CoffeeScript classes.

0.2.0Oct 25, 2010
Instead of requiring server responses to be namespaced under a model key, now you can define your own parse method to convert responses into attributes for Models and Collections. The old handleEvents function is now named delegateEvents, and is automatically called as part of the View's constructor. Added a toJSON function to Collections. Added Underscore's chain to Collections.

0.1.2Oct 19, 2010
Added a Model#fetch method for refreshing the attributes of single model from the server. An error callback may now be passed to set and save as an option, which will be invoked if validation fails, overriding the "error" event. You can now tell backbone to use the _method hack instead of HTTP methods by setting Backbone.emulateHTTP = true. Existing Model and Collection data is no longer sent up unnecessarily with GET and DELETE requests. Added a rake lint task. Backbone is now published as an NPM module.

0.1.1Oct 14, 2010
Added a convention for initialize functions to be called upon instance construction, if defined. Documentation tweaks.

0.1.0Oct 13, 2010
Initial Backbone release.


A DocumentCloud Project