Backbone.js: Should .render () and .remove () be able to reverse each other?

Since Backbone.js is quite flexible, I am wondering which approach is best for certain things. Here I am wondering if I should build my applications so that ".render ()" and ".remove ()" correctly change each other.

First, the path that seems the cleanest is to pass the view to an identifier or jQuery element to join. If everything is done like this, but calling ".render ()" incorrectly replaces the view in the DOM, since the main element never returns to the DOM:

App.ChromeView = Backbone.View.extend({
  render: function() {
    // Instantiate some "sub" views to handle the responsibilities of
    // their respective elements.
    this.sidebar = new App.SidebarView({ el: this.$(".sidebar") });
    this.menu = new App.NavigationView({ el: this.$("nav") });
  }
});

$(function() {
  App.chrome = new App.ChromeView({ el: $("#chrome") });
});

It seems to me preferable to tweak it so that .remove () and .render () are exact opposites:

App.ChromeView = Backbone.View.extend({
  render: function() {
    this.$el.appendTo('body');
    this.sidebar = new App.SidebarView({ el: this.$(".sidebar") });
    this.menu = new App.NavigationView({ el: this.$("nav") });
  }
});

$(function() {
  App.chrome = new App.ChromeView();
});

Backbone.js? .remove() .render() ?

+3
3

, render view dom. , , , . "".

remove , , , , , . DOM- HTML (#main - ) . .

, , jQuery, , DOM. postAttach() , .

+2

, View.remove() .

el :

remove: function(){
  this.$el.empty();
  return this;
}

, , DOM-.

, , , , .

+2

? .initialize .render, parentSelector, :

  • .remove()/. render()

:

// Bootstrap file
curl(['views/app']).then(
    function(App){
        app = new App('body');
    });



// view/app.js
   define([
        'text!views/app.tmpl.html'
    ,   'link!views/app.css'
    ]
,   function (template) {

    var App

    // Set up the Application View
    App = Backbone.View.extend({
        // Standard Backbone Methods
        initialize: function (parentSel) {
            console.log('App view initialized')
            if (parentSel) { this.render(parentSel) }
        }
    ,   render: function (parentSel) {
            if (parentSel) { this._sel = parentSel } // change the selector if render is called with one
            if (!this._sel) { return this } // exit if no selector is set

            this.$el.appendTo(this._sel)

            this.$el.html(
                this.compiledTemplate({ 'content':'test content' })
            );
            return this
        }
        // Custom Properties
    ,   compiledTemplate: _.template(template)
    })

    return App
});


// External usage
// I can call .remove and .render all day long now:
app.remove()
app.render()
app.remove()
0

All Articles