When you create a controller and also generate a jquery plug-in, you can complete the following functions: 1. generate Controller on one or more HTML elements; 2. call the constructor. 3. update the controller.
Let's look at the example of the controller below:
$. Controller ("My. widget", {Say:Function() {Alert (This. Options. Message );}})
CreatedJquery. FN. my_widget plug-in, you can use it like this:
//Create my_widget in every. Thing$ (". Thing"). my_widget ({message: "Hello"})//"Hello" is displayed"$ (". Thing"). my_widget ("say");//Update message$ (". Thing"). my_widget ({message: "world"});//Pop up "world"$ (". Thing"). my_widget ("say ");
Create a controller
When the controller is used on the jquery selector, it traverses every related HTML element to see if they have a controller instance. If not, it is created. It will call New yourcontroller () on your element and pass the parameter to the Controller. For example, we have two. Thing elements,
$ (". Thing"). my_widget ({message: "Hello "})
This sectionCodeIt is equivalent to the following code:
VaRThings = $ ('. th'), Options= {Message: "Hello"};NewMy. widget (things [0], Options );NewMy. widget (things [1], options );
When a controller is created, it calls the setup and init methods in prototype.
Call the method on the Controller
After a controller is created on an HTML element, you can call the preceding method. The first parameter is the method name, followed by the required parameters of the method, as shown in the following example:
$. Controller ("adder", {Sum:Function(First, Second, Third ){This. Element. Text (first + second +Third );}})//An adder is added to the page.$ ("# Myadder"). Adder ()//Show the result of 1 + 2 + 3$ ("# Myadder"). adder ("sum", 1, 2, 3 );
Name
By default, the plug-in name is the Controller name, but the following changes will be made:
1. Use jquery. String. Underscore () to process the name string, for example:
Jquery. String. Underscore ("onetwo ")//-> "One_two"
2. Use '_' instead '.'.
3. Remove'Controllers'.
$. Controller ("foo ")//->. Foo ()$. Controller ("foo. Bar ")//->. Foo_BAR ()$. Controller ("foo. controllers. Bar ")//->. Foo_BAR ()
You can also set staticPluginname attribute to change the default name of the controller.
$. Controller ("My. Tabs", {Pluginname:"Tabs"}, {...}) $ ("# Tabs"). tabs ()