簡體   English   中英

骨干網,如何確保在視圖內部聲明的函數僅影響該視圖中的DOM元素?

[英]Backbone, how to ensure that the functions declared inside the view, affect DOM elements from that view only?

以下視圖綁定到cars元素。

初始化視圖時,我加載了一個特定的模板,該模板加載了一個名為“ .menu”的div。

現在,我想對該菜單進行處理,並用hmtl填充它,並且只希望影響視圖內部的菜單。

如果該頁面在視圖之外還有另一個“菜單”,它將受到影響。

如何確保視圖內的JavaScript僅影響該視圖中的元素?

var myView = Backbone.View.extend({

    el : '.cars',

    pag : '.pagination',

    initialize : function () {

        var template = _.template(myTemplate, {});

        $(this.el).html(template);

        $('.menu').html('test');
    },

    events : {
    'click .pagination a' : 'click'
},

});

我可以這樣做:

$('.cars .menu').html('test');

但是我認為應該有一個更優雅的解決方案,例如將.menu綁定到視圖。

第二個問題...

如果我將click事件綁定到視圖內名為.pagination的div ...我如何在事件對象中使用變量而不是寫元素的名稱?

視圖的el的html可以使用find來確定范圍:

yourView.$el.find(".menu");

或通過上述方法的快捷方式:

yourView.$(".menu");

考慮到您的第二個問題,您還可以將事件綁定到視圖中的元素:

 // in the model definition
 events: {
   // This would only bind to clicks for .pagination elements that are
   // children of the view
   'click .pagination a' : function (e) {
      // You can get at the clicked element via the `currentTarget` property 
      // of the event
      var href = $(e.currentTarget).attr('href');
      console.log(href);
   }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM