0

有点像一个JavaScript 新手,阅读了一个骨干网教程http://arturadib.com/hello-backbonejs/docs/5.html并对作者使用的一些代码有一些疑问。

在下面的初始化函数中,作者绑定了

  this.model.bind('change', this.render);
  this.model.bind('remove', this.unrender);

我假设这意味着render每当调用更改函数时都会在“this”对象上调用该函数,并且unrender每当remove调用该函数时都会运行该函数。对我来说,问题是他的代码中有一个定义的函数'remove',但没有定义的函数'change'

问题:做changeremove引用jquery函数还是remove函数引用remove代码中定义的函数(即它覆盖jquery函数)而change引用jquery函数。'change'如果是后者,如果从未显式调用该函数并因此触发该函数,究竟是什么触发了该render函数?

代码

var ItemView = Backbone.View.extend({
    tagName: 'li', // name of tag to be created        


    events: { 
      'click span.swap':  'swap',
      'click span.delete': 'remove'
    },    


    initialize: function(){
      _.bindAll(this, 'render', 'unrender', 'swap', 'remove'); // every function that uses 'this' as the current object should be in here

      this.model.bind('change', this.render);
      this.model.bind('remove', this.unrender);
    },


    render: function(){
      $(this.el).html('<span style="color:black;">'+this.model.get('part1')+' '+this.model.get('part2')+'</span> &nbsp; &nbsp; <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
      return this; // for chainable calls, like .render().el
    },


    unrender: function(){
      $(this.el).remove();
    },


    swap: function(){
      var swapped = {
        part1: this.model.get('part2'), 
        part2: this.model.get('part1')
      };
      this.model.set(swapped);
    },



    remove: function(){
      this.model.destroy();
    }
  });

​</p>

4

1 回答 1

2

changeand是 Backbone 事件,而remove不是 jQuery 事件。这些:

this.model.bind('change', this.render);
this.model.bind('remove', this.unrender);

表示this.render模型触发事件时调用,模型触发change事件this.unrender时调用remove。模型上的set方法

model.set(attributes, [options])

在模型上设置属性的散列(一个或多个)。如果任何属性更改模型状态,"change"则会触发事件,除非{silent: true}作为选项传递。

change是触发模型事件的一种方式unsetclear也会触发change事件。

remove事件通常来自集合,但集合将通过适当的模型发送它们,以防有视图监听。

您可能想阅读(相当不错的)Backbone 文档并特别查看事件目录

于 2012-04-11T04:01:48.860 回答