How do you call a function from a jQuery controller?
I'm using JavascriptMVC and have a controller of the form
$.Controller.extend('AppName.Controllers.ControllerName',
{
onDocument: true
}
{
initControllerName: function() {
...
},
testFucntion1() {
alert('yeah!!');
}
});
and I'd like to be able to call the function testFunction1() from the page ge开发者_StackOverflow社区nerated by my view.
I found this question which seems to be asking the same thing, but I wasn't able to figure it out with the answer provided there.
I've tried
$('#controllername').testFunction1();
$('#ppame_controllername').testFunction1();
$('#ppame_controllers.controllername').testFunction1();
without success.
Thanks for your help!!
Martin Owen's answer is accurate except I found app_name_controller_name confusing at first.
A real example would be:
if your controller is defined like
$.Controller.extend('Layout.Controllers.Page',
...
then use
$(document).layout_page("testFunction1");
Layout = app_name
Page = controller_name
You can call your function with:
$(document).app_name_controller_name("testFunction1");
If you want to pass arguments to your function specify them after the function name:
$(document).app_name_controller_name("testFunction1", "Hello World");
The onDocument: true
in the static section of your controller definition means that it is automatically attached to the document element, so that is how you get an instance of it. If you want to bind it to something else remove onDocument: true
and use something like:
$('#main').app_name_controller_name();
That will create an instance of your controller and attach it to the $('#main') element. That element is then available in the controller's methods via this.element
.
I don't know your situtation but you shouldn't really need to call controller methods very often - the controller should bind to events that are triggered by DOM elements and published by models. JMVC makes it very easy to bind controller methods to events: Listening To Events
精彩评论