Jeevi
Jeevi

Reputation: 1052

Ember call a action handler from normal Javascript

I am working in Ember with my existing jQuery. Now I need to call a action handler in my Router from my jQuery method.

My Route:

App.ApplicationRoute: Ember.Route.extend({
    actions: {
        updateFolder: function(obj){
             //Need to update my model using the obj.
        }
    }
});

My JavaScript method:

// Native Javascript code. 
function updateFolderModel(obj){
    // Need to call the action handler in my application route. How to call from here.
} 

How can I call Ember action handlers from normal native JavaScript methods.

Upvotes: 1

Views: 1410

Answers (1)

yorbro
yorbro

Reputation: 1137

You don't want your outside code to know about your Ember application. The best way to deal with this in this case is using DOM events. DOM events would be the means of communication between your Ember application and the "outside world". See http://emberjs.com/api/classes/Ember.View.html#toc_responding-to-browser-events for some documentation on this.

For instance

App.ApplicationView = Ember.View.extend({
  // See comment by @Wishy
  click: function() {
    this.send('actionThatWillBeSentToYourRoute');
  },
  /*
  didInsertElement: function() {
    var self = this;
    // Replace 'click' with a custom DOM event
    this.$().on('click', function() {
      Ember.run(self, function() {
        this.send('actionThatWillBeSentToYourRoute');
      });
    });
  }
  */
});

The Ember.run is required because you want to run the callback inside the Ember runloop. Note that it is a bit cleaner to register your custom DOM events as in http://emberjs.com/api/classes/Ember.Application.html#property_customEvents.

Then in your Route you would have

App.ApplicationRoute = Ember.Route.extend({
  actions: {
    actionThatWillBeSentToYourRoute: function() { ... }
  }
});

Note that you can define your own custom DOM events, for instance an event updateFolder. Then you can do

function updateFolderModel(obj){
  $.trigger('updateFolder', obj);
}

I hope this is of any help!

Upvotes: 2

Related Questions