步骤 2: 使用事件解除依赖.这个例子,利用MVC框架是关键。我们将会用到事件机制, 事件使我们结合和触发自定义事件. 因此,我们创建新的“AnimalsView”和“NewAnimalView”,并且赋予它们不同的显示animals的职责。 使用事件就来区别职责非常简单。如果在方法和事件之间传递职责,如下所示: 01 | var events = _.clone(Backbone.Events); |
02 | var Animals = function () { |
05 | Animals.prototype.add = function (text) { |
11 | success: function (data) { |
12 | events.trigger( 'animal:add' , data.text); |
17 | var NewAnimalView = function (options) { |
18 | this .animals = options.animals; |
19 | events.on( 'animal:add' , this .clearAnimal, this ); |
20 | var add = $.proxy( this .addAnimal, this ); |
21 | $( '# form' ).submit(add); |
24 | NewAnimalView.prototype.addAnimal = function (e) { |
26 | this .animals.add($( '#new-animal textarea' ).val()); |
29 | NewAnimalView.prototype.clearInput = function () { |
30 | $( '#new-animal textarea' ).val( '' ); |
33 | var AnimalsView = function () { |
34 | events.on( 'animal:add' , this .appendAnimal, this ); |
37 | AnimalsView.prototype.appendAnimal = function (text) { |
38 | $( '#animals ul' ).append( '<li>' + data.text + '</li>' ); |
41 | $(document).ready( function () { |
42 | var animals = new Animals(); |
43 | new NewAnimalView({ animals: animals }); |
步骤 3: 传递数据结构到核心框架最后,最重要的一步,我们使用: models, views and collections. 01 | var Animal = Backbone.Model.extend({ |
05 | var Animals = Backbone.Collection.extend({ |
09 | var AnimalsView = Backbone.View.extend({ |
10 | initialize: function () { |
11 | this .collection.on( 'add' , this .appendAnimal, this ); |
14 | appendAnimal: function (animal) { |
15 | this .$( 'ul' ).append( '<li>' + animal.escape( 'text' ) + '</li>' ); |
20 | var NewAnimalView = Backbone.View.extend({ |
22 | 'submit form' : 'addAnimal' |
25 | initialize: function () { |
26 | this .collection.on( 'add' , this .clearInput, this ); |
29 | addAnimal: function (e) { |
31 | this .collection.create({ text: this .$( 'textarea' ).val() }); |
34 | clearInput: function () { |
35 | this .$( 'textarea' ).val( '' ); |
39 | $(document).ready( function () { |
40 | var animals = new Animals(); |
41 | new NewAnimalView({ el: $( '#new-animal' ), collection: animals }); |
42 | new AnimalsView({ el: $( '#animals' ), collection: animals }); |
|