【问题标题】:Triggering and Listening to Events across different classes in Backbone - In CoffeeScript在 Backbone 中跨不同类触发和监听事件 - 在 CoffeeScript 中
【发布时间】:2012-08-16 19:30:48
【问题描述】:

基本上我是 Backbone 的新手。从我的角度来看,我正在更改我的集合中名为“limit”的属性。然后我试图触发一个事件(当一个属性刚刚改变时),让我能够监听事件并执行其他操作。

但是,当某些内容发生更改时从我的集合中触发一个事件,并在发生更改时侦听该更改是行不通的。我认为这与视图和集合相互通信有关。任何帮助将不胜感激!谢谢

触发事件的代码(在我的收藏中)是:

@trigger("change") #TRIGGER THE EVENT

更改我的集合中属性的代码(有效)是:

@Properties.attr("limit", "1000") #Change the limit attr to "1000"

监听变化的代码(不起作用)是:

@Properties.on("change", ->
     alert("Attribute has been changed!")
)

完整的代码是:

class PropertyCollection extends Backbone.Collection
        model: Property

        constructor: ->
            super

        initialize: ->
            @_attr = {}

        #Function to change attribute of collection 
        attr: (prop, value) ->
            if value is undefined
                @_attr[prop]
            else
                @_attr[prop] = value
                @trigger("change") #TRIGGER THE EVENT

        limit: "0" #Attribute - default is set to 0



    class HomeView extends Backbone.View
        constructor: ->
            super

        initialize: ->
                @Properties = new PropertyCollection

                @Properties.attr("limit", "1000") #Change the limit attr to "1000"

                #Listen for the change
            @Properties.on("change", ->
                 alert("Attribute has been changed!")
            )

        template: _.template($('#home').html())

        render: ->
            $(@.el).html(@template)

【问题讨论】:

    标签: javascript jquery backbone.js coffeescript backbone-events


    【解决方案1】:

    您在进行更改后注册以监听该更改

    更改属性->触发事件->无人监听->注册监听

    所以改变这个:

    initialize: ->
      @Properties = new PropertyCollection
    
      @Properties.attr("limit", "1000") #Change the limit attr to "1000"
    
      #Listen for the change after the firing of the change (why?!!!)
      @Properties.on("change", ->
        alert("Attribute has been changed!")
      )
    

    到这里

    initialize: ->
      @Properties = new PropertyCollection
    
      #Listen for the change BEFORE you make it (yes yes yes!!!)
      @Properties.on("change", ->
        alert("Attribute has been changed!")
      )
    
      @Properties.attr("limit", "1000") #Change the limit attr to "1000"
    

    希望这会有所帮助!

    【讨论】:

    • 啊,如此明显和简单!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2013-12-29
    相关资源
    最近更新 更多