As part of upgrading from jQuery 1.6.4 to 1.9.x, I'm trying to understand how to use jQuery widget bridge to allow access to functions for widgets created as a standalone object, rather than as an extension to jQuery.
All of the examples (like this one) use a prototype function as the source definition of the object, which doesn't seem to map for defining an object directly from a {} based definition.
For example I am defining a widget like this:
var ControlPanel = {
instance: null,
options: {
//Some options here
},
simpleFunction: function(){
alert("I am a function");
},
_init: function() {
//Some init stuff here
}
}
$.widget("basereality.controlPanel", ControlPanel); // create the widget
//This doesn't appear to work...
$.widget.bridge('controlPanel', $.basereality.controlPanel); //'Bridge' the widget
And then creating an instance of it by doing:
var controlPanelParams = {
// some options go here
};
var newControlPanel = $('#controlPanel').controlPanel(controlPanelParams);
I would now like to be able to call the method 'simpleFunction' on the created object, which I've tried to do by doing:
newControlPanel.simpleFunction();
//and
$(newControlPanel).simpleFunction();
Both of which give a 'Object does not have a method called simpleFunction' error.
So what am I doing wrong and how are you meant to use $.widget.bridge on non-function based objects?
I think I've figured it out. Instead of this:
$(newControlPanel).addControl(smartyControlPanel);
Access the function by calling it as a parameter like this:
newControlPanel.controlPanel("addControl", smartyControlPanel);
And I also converted my code to have be based of a function for the first prototype:
var ControlPanel = function(options, element){
this.options = options;
this.element = element;
this._init();
};
ControlPanel.prototype = {
//Everything else in here
}
Though having to call it as a parameter is a lot less easy to understand than it was calling it directly as a function.