简体   繁体   中英

Where I can write helper in ember to avoid code duplication

I have a couple lines of duplicate code

Ember.$(".close").trigger('click'); window.parent.showRegister();

in: adapters , controllers and routes .

Where the best place to write helper (function or action) and executing this in different places.

For example I can write function in controller , but I don't know how access controllers in RESTAdapter .

The main reason why you can or can't access to some abstractions from another is control of software complexity, an attempt to keep it to a minimum. There are principles like SOLID , low coupling / high cohesion to follow which helps us to maintain complex software systems, to increase comprehensibility of a system and to decrease possibility of an error in development process.

Ember is follow the MVC pattern in some way, and because of that I wouldn't advise (1) to keep code for DOM manipulation in controller/adapter/router and (2) to couple adapters, controllers and routes in such a way. I'am sure there is a way to put this code in View or in module outside of Ember.App classes; or to set up routing map handling this case.

If it's not the case or you need a simple and straight solution, you can use ugly-magic constructions to access anything from everywhere in Ember:

App.__container__.lookup('controller:controllerName'); // controllers
App.__container__.lookup('router:main'); // routes
App.__container__.lookup('store:main'); // store, adapters, serializers
Ember.View.views['emberViewId'] // objects are dying here occasionally

Double underscore tells us that this is not the recommended way to build communications in application. :)

You can create a new Ember Object with helper as a method in it.

Then you can register these helper in Application and inject it in controller , model and views.

see http://emberjs.com/guides/understanding-ember/dependency-injection-and-service-lookup/#toc_dependency-injection-with-code-register-inject-code for more details

App = Ember.Application.extend();
Ember.Application.initializer({
   name: 'logger',
   initialize: function(container, application){
   application.register('logger:main', {log: function(m){ console.log(m); }}, {instantiate: false});
   application.inject('route', 'logger', 'logger:main');
   }
});
App.create();

And use it like

App.IndexRoute = Ember.Route.extend({
   activate: function(){
   // The logger property is injected into all routes
   this.logger.log('Entered the index route!');
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM