Search code examples
javascriptbackbone.js

Is it possible within Backbone.js to reload route with history.loadUrl and pass in a string to be used as success message?


I am having trouble working out if it is possible to pass a string into a view using backgone.history.loadUrl?

//My current method of reloading the view    
Backbone.history.loadUrl(Backbone.history.fragment);

I would like to use this method if possible so that it renders the view from the Backbone router rather then rendering my view again from within itself and passing it in as the options for that view.

//Destroy old view
//Render view again    
var view = new myView("success msg");

Solution

  • Here's a simple way to extend Backbone.history with a reload function:

    _.extend(Backbone.history, {
        reload: function(){
            return this.loadUrl(this.getFragment());
        }
    });
    

    Don't do this if you're writing a library/plugin.

    Then calling Backbone.history.reload(); anywhere will call the route again.

    Is it a good way to re-render a view? No.

    If you want to re-render a view within itself, do that, don't reload the whole route.

    var View = Backbone.View.extend({
        // events, etc. ...
        render: function() {
            // rendering
            if (this.success) {
                // show success message
            }
            return this;
        },
        onMyEvent: function() {
            // here, a re-render with a success message is necessary
            this.success = true;
            this.render();
        }
    })