Remove li from Ul backbone

[亡魂溺海] 提交于 2019-12-08 08:21:28

I think you need a more modular approach to Backbone, let me explain.

Backbone is a way to organize your code. Having just one Backbone view do it all, doesn't change a lot.

Instead, try to see what views you actually need:

  • MainView
  • ListView
  • ListItemView

MainView could look like this:

var MainView = Backbone.View.extend({

    el: 'body',

    initialize : function(options) {
       this.collection = new Backbone.Collection.extend({ url: '/items' });
    },

    events:{
    },

    render:function(){
        var listView = new ListView({ el: this.$("#myList") });
        listView.render();

        this.collection.fetch();

        return this;
    }
});

ListView

var ListView = Backbone.View.extend({

    tagName: 'ul',

    initialize : function(options) {
        _.bindAll(this, "render");

        this.collection.on("add", this.appendListItem, this);
    },

    events:{
    },

    render: function() {
        this.collection.each(this.appendListItem, this);

        return this;
    },

    appendListItem: function (model, collection, options) {
        var listItem = new ListItemView({ model: model});
        this.$el.append(listItem.render().el);
    }
});

ListItemView

var ListItemView = Backbone.View.extend({

    tagName: 'li',

    initialize : function(options) {
        _.bindAll(this, "render");

        this.model.on("destroy", this.remove, this);
    },

    events:{
        "click button": "delete"
    },

    render:function(){
        this.$el.text(this.model.get('name'));
        this.$el.append("<button class='button'>Delete</button>");

        return this;
    },

    delete: function (event) {
        this.model.destroy();
    }
});

Kick off the main view: var view = new MainView().render();

Pramod

A unique id must be assigned to each li element when you render each model on the UI to know which element gets deleted.

Instead of

$('#mylist').append('<li>'+model.get('name') + "<button class='button'>"+"delete"+"</button></li>");

you're better off using templates. You can use underscore's template which will it easier to assign ids and create lis dynamically.

To delete the model:

removefoo:function(evt){
        var target = evt.target;
        //Parse the target id to get the model id and then delete it.
    }

See https://stackoverflow.com/questions/8782704/backbone-js-tutorial to understand how all the components of backbone fit together.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!