alert window in a different view after form submit

2019-08-26 10:30发布

问题:

Using backbone.js, and I have a form that I am able to submit and after submitting, the savepost() function redirects it to the dashboard url. The dashboard is a different view, and would like that page to say "your post was submitted". I could use localstorage, but do not want to depend on it.

I also see the popular event aggregator options, but not sure if that would work on views being rendered in the a different page.

回答1:

Sounds like you need a global event bus.

Here's a great example jsfiddle, author is credited in the fiddle

https://jsfiddle.net/JamesOR/m8J9L/

var eventBus = _.extend({}, Backbone.Events);

Then, inside the dashboard view, listen for the event. In the fiddle you'll notice the author uses .on. This is old style, the backbone author now recommends listenTo, because once the view is removed, all listeners are removed automatically. This is not the case with on

initialize: function () {
    this.listenTo(eventBus,'formSubmitted',this.onFormSubmit);
}

Then, when the form is submitted, trigger the event.

eventBus.trigger('formSubmitted', /** data that you want to send to handler*/);

In the handler method

onFormSubmit:function(/** data that sent to this handler*/){
    //code here
}