簡體   English   中英

第一次單擊后丟失主干視圖事件處理

[英]Backbone view event handling lost after first click

我對javascript很陌生,並且有一個簡單的頁面,該頁面在右上角顯示購物車摘要。

點擊之前

第一次單擊更新按鈕時,將按預期更新集合和視圖。

第一次點擊后

但是,隨后的單擊無效,並且控制台中沒有錯誤。 第一次單擊后,事件處理似乎丟失了。

我注意到在SO上發布了其他類似的問題,這些問題指向在調用.html()后在視圖對象上調用委托事件的解決方案。 我已經嘗試過了,但是沒有什么區別。

我的骨干觀點是:

MyApp.View.Item = Backbone.View.extend({

    events: {
        'click #update-btn' : 'update',
        'click #reset-btn' : 'reset'
     }, 

     initialize: function(){
         console.log('item view initialize invoked');
         this.collection = new MyApp.Collection.Items();
         this.listenTo(this.collection, 'add', this.display);
         var source = $("#cart-template").html();
         this.template = Handlebars.compile(source);
     },

     render: function(){
         console.log('render invoked');
         var html = this.template(this.collection);
         this.$el.html(html);
         // this.delegateEvents(); <-- Tried this
         return this;
    },

    display: function() {
        $('#cart-summary').html(this.render().el);
    },

    update: function(e) { 
        console.log('update invoked');
        e.preventDefault();
        var newItem = new MyApp.Model.Item();
        newItem.setName('blah');
        newItem.setPrice(20);
        this.collection.addItem(newItem);
    },  

    reset: function(e) { 
        console.log('reset invoked');
        e.preventDefault();
    }
});

我的收藏是

MyApp.Collection.Items = Backbone.Collection.extend({

    initialize: function(){
        this.items = 0;
        this.total = 0;
    },

    addItem: function(item) {
        console.log('addItem invoked');
        this.items++;
        this.total += item.getPrice();
        this.trigger('add');
   }

});

我正在使用骨干1.1.2,jquery 2.1.1和Chrome 35.0.1916.153。

提前致謝。

首先,在創建視圖時,應將el設置為#chart-summary。

MyApp.View.Item = Backbone.View.extend({

    el: '#cart-summary'

    (your other stuff)
});

並嘗試如下更改顯示功能

display: function() {
    this.render();
},

一個教程示例http://backbonetutorials.com/what-is-a-view/ ,使用以下行創建了一個新視圖:

var view = new MyApp.View.Item({el:$(“#'div容器ID,其中包含按鈕視圖'”)});

我認為它提供了刷新的視圖,單擊后按鈕將起作用。 我認為這應該是主干視圖中的最后一行代碼。 也許您已經在執行此操作,但是我無法在您的代碼中看到它。

暫無
暫無

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

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