I have a simple jQuery function with optional parameters, All I want is to pass control name, event name and value or function name than bind it to the passed control.
jQuery Function
BindEvents: function (options) {
var defaults = {
Control: null,
Events: null
}
settings = $.extend({}, defaults, options);
if (Events != null) {
$(Control).on(Events['name'], function () {
'How to call passed function';
});
}
}
Calling the Function
$.fn.BindEvents({
Control: "#txtTest",
Events: { "name": "focus", "value": "$.fn.test()" }
});
1) You forgot to use 'settings' prefix:
BindEvents: function (options) {
// defaults do not make sense this way, but they probably have a sane default in your code, right?
var defaults = {
Control: null,
Events: null
}
settings = $.extend({}, defaults, options);
if (settings.Events != null) {
$.each(settings.Events, function(eventName, handler) {
$(settings.Control).on(eventName, handler);
});
}
}
2) call BindEvents with an function reference instead of a string. I also changed the Event object a bit:
$.fn.BindEvents({
Control: "#txtTest",
Events: { "focus": $.fn.test }
});
Related
I have my javascript code like this . Inside that I have an init() function and in that function I have an options JSON object and in that object I have a function defined as objectselected(). How I call that function in a button click event
I have tried like this WorkFlow.init().options.Objectselected() but it is not working,
var WorkFlow = {
connectionData: [],
selectedTouchpoints: [],
init: function () {
var options = {
palleteId: "myPaletteElement",
elementId: "playAreaContainer",
TextStoreList: ['One', 'Two', 'Three'],
LinkTextStoreList: $('#drpLinkType option').map(function () {
return this.text;
}).get(),
shapeList: ['RoundedRectangle', 'Circle', 'Rectangle', 'Ellipse', 'Square', 'Diamond', 'Card', 'Database'],
diagramUpdate: function (e) {
},
objectSelected: function (e) {
},
linkUpdate: function (e) {
},
initialize: function () {
}
myGraph = new Graph(options);
options.initialize();
},
}
How to call that function.
One way around is you can return options and than call it.
init: function () {
var options = {
...your code..}
return options;
},
and call it than
var options = WorkFlow.init();
options.Objectselected();
As it stands, you have no access to options because it's a local variable - that is, local to its scope.
To access its contents, you'll need to return it from init().
Think about it:
WorkFlow.init()
Currently this returns undefined, because your init() returns nothing. You're trying to chain like in jQuery, but that relies on the API always returning the instance. Your path finds a dead-end at init().
To fix this, have init() return options - or at least the part of it you want to access from outside - an "export".
So (basic example)
init: function() {
var options {
my_func: function() { }, //<-- we want outside access to this
private: 'blah' //<-- this can stay private - leave it out of the export
}
//return an export, exposing only what we need to
return {
my_func: options.my_func
}
}
You need to return options as it is inside init function's scope
var WorkFlow = {
connectionData: [],
selectedTouchpoints: [],
init: function () {
var options = {
palleteId: "myPaletteElement",
elementId: "playAreaContainer",
TextStoreList: ['One', 'Two', 'Three'],
LinkTextStoreList: $('#drpLinkType option').map(function () {
return this.text;
}).get(),
shapeList: ['RoundedRectangle', 'Circle', 'Rectangle', 'Ellipse', 'Square', 'Diamond', 'Card', 'Database'],
diagramUpdate: function (e) {
},
objectSelected: function (e) {
},
linkUpdate: function (e) {
},
initialize: function () {
}
myGraph = new Graph(options);
options.initialize();
return options;
},
}
And call it as WorkFlow.init().objectSelected();
Building on Patrick's comment, you'd need to return options from the init function:
var WorkFlow = {
connectionData: [],
selectedTouchpoints: [],
init: function () {
var options = {
palleteId: "myPaletteElement",
...
options.initialize();
return options;
},
}
I'm trying to figure out how to use this._super when the Ember's object method is called from a callback.
I know that I could assign var _super = this._super before the callback is called but I don't like it.
I want to have the this object containing proper _super method inside the callback.
My code is here: http://emberjs.jsbin.com/hasehija/6/edit.
App.BaseMixin = Ember.Mixin.create({
init: function() {
console.log("base");
}
});
App.Utils = Ember.Object.extend({
callbackMethod: function(callback, ctx) {
// asynchronous callback
Ember.run(function() {
callback.call(ctx);
});
}
});
App.MyObject = Ember.Object.extend(App.BaseMixin, {
init: function() {
console.log("MyObject");
var _super = this._super;
App.Utils.create().callbackMethod(function() {
this._super(); // this._super is undefined here
// _super() would work
}, this);
}
});
App.ApplicationController = Ember.Controller.extend({
init: function() {
new App.MyObject();
}
});
Do you know any way to fix it?
UPDATE:
It turned out that it was fixed in Ember 1.5.0 (#GJK: thank you for the answer) and I was using Ember 1.4.0.
extend defines a class
App.Utils = Ember.Object.extend({
callbackMethod: function(callback, ctx) {
callback.call(ctx);
}
});
create builds an instance of the class
App.Utils = Ember.Object.create({
callbackMethod: function(callback, ctx) {
callback.call(ctx);
}
});
or
App.Utils.create().callbackMethod(function() {
this._super();
}, this);
http://emberjs.jsbin.com/hasehija/7/edit
Or avoid overriding init
App.ApplicationController = Ember.Controller.extend({
doSomething: function() {
new App.MyObject();
}.on('init')
});
How could I call the function 'gotopage' below in javascript?
I used 'gotopage(5);',but the browser points out the function is not defined.So what is the correct answer to call the function in others' jQuery plugin?
;(function ($) {
$.fn.booklet = function (options, param1, param2) {
//..............
};
function Booklet(inTarget, inOptions) {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
return {
init: init,
enable: enable,
disable: disable,
destroy: destroy,
next: next,
prev: prev,
gotopage: function (index) {
//.............
goToPage(index);
},
add: addPage,
remove: removePage,
option: function (name, value) {
//.............
}
}
}
// define default options
$.fn.booklet.defaults = {
//...........
}
})(jQuery);
"goToPage" is a function "inside" another function "Booklet" and this again is inside another anonymous function (as far as I can see).
You can't call this function directly from outside this function. You need to call if from the same scope.
And here is the solution quickly found by reading the Plugin Documentation:
$('#custom-goto').click(function(e){
e.preventDefault();
$('#mybook').booklet("gotopage", "end");
});
goToPage(index) is a private function it couldn't be called outside the plugin.Try creating function globally using $.fn.
$.fn.goToPage=function(index){
}
Hope this helps ..i haven't tried testing it
`(function ($) {
$.fn.booklet = function (options, param1, param2) {
//..............
};
function Booklet(inTarget, inOptions) {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PUBLIC FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
return {
init: init,
enable: enable,
disable: disable,
destroy: destroy,
next: next,
prev: prev,
gotopage: function (index) {
//.............
$.fn.goToPage(index);
},
add: addPage,
remove: removePage,
option: function (name, value) {
//.............
}
}
}
// define default options
$.fn.booklet.defaults = {
//...........
}
$.fn.goToPage=function(index){
//function is now public
};
})(jQuery);
`
Hello I have this code which works fine
var app = {
callback: null,
jqmReady: null,
pgReady: null,
// Application Constructor
initialize: function(callback) {
this.callback = callback;
this.jqmReady = $.Deferred();
this.pgReady = $.Deferred();
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', app.pgReady.resolve, false);
$(document).on("pageinit", app.jqmReady.resolve);
$.when(app.jqmReady, app.pgReady).then(app.isReady);
},
isReady: function() {
app.callback();
}
};
code is being initialized like this:
app.initialize(function(){
navigator.notification.alert('Hello there!', function(){}, 'Notify', 'Ok');
});
however my isReady function was like this at first and the callback was not called:
isReady: function() {
this.callback();
}
Why is this happening ? isn't the scope of this = app inside isReady() like in the initialize() function ?
Could someone explain to me why it doesn't work with this.callback() ?
You've created an object, not a class or an instance of a class. Change your this to app throughout your initialize function. You're doing that already in your isReady and bindEvents functions. So keep that going in initialize.
I am trying to create a js object, I want either the user passes in some json data or the objects properties are set by default as shown below. After that is all set, I finally want to call an init function that runs and does the work. Thanks for any help. I am not trying to create a jQuery plugin.
var PictureDialog = function (settings) {
settings = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1,
init: function() {
//Do work
//Show dialog
}
},settings;
}
Would the call look something like this
PictureDialog({prevID:1}).init();
Not sure why you would need an init function at all. This is how I would do it:
(function () {
var defaultSettings = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1
};
PictureDialog = function (settings) {
settings = settings || defaultSettings;
//Do work
//Show dialog
};
})();
The outer function is just to make sure that defaultSettings doesn't pollute the global scope.
If I understand correctly you want to set some default values, with the help of jQuery you can use $.extend like this:
function Foo( settings ) {
var _defaults = { a: 'a', b: 'b' };
settings = $.extend( settings, _defaults );
}
With pure JavaScript you'd have to do something like this:
function Foo( settings ) {
var _defaults = { a: 'a', b: 'b' };
settings.a = settings.a || _defaults.a;
settings.b = settings.b || _defaults.b;
}
As for the init method, you can just add it to the prototype and execute it in the constructor so you don't even have to call it when you create a new instance:
function Foo( settings ) {
var _defaults = { a: 'a', b: 'b' };
...
this.init();
}
Foo.prototype = {
init: function() {
console.log('initialized!');
}
}
The quick and simple way would be this:
var PictureDialog = function (settings)
{
settings = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1,
init: function()
{
//Do work
//Show dialog
return this;//<--return object, too
}
};
return settings;//return the object
};
foo = PictureDialog().init();//the init will be called on the return value of PictureDialog
I don't, however, get why the PictureDialog function expects a settings argument. Either pass nothing to the function at all, or alter the passed value:
var PictureDialog = (function()
{
var defaults = {
allowShortKey: true,
prevID: null,
prevCounterNumber: null,
startValue: 0,
nextValue: 1,
init: function()
{
//Do work
//Show dialog
return this;//<--Very important
};
return function (settings)
{
settings = settings instanceof Object ? settings : {};
for (var n in defaults)
{
if (defaults.hasOwnProperty(n))
{//set all properties that are missing from argument-object
settings[n] = settings[n] || defaults[n];
}
}
return settings;
};
}());
foo = PictureDialog({allowShortKey: false}).init();//will return full settings object