How could I call function in a jQuery plugin? - javascript

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);
`

Related

Calling a private/nested javascript function from an outer scope

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;
},
}

Should my factory return an object with helper methods or should I use prototype?

I'm a beginner with angular and I try to understand if I should user a factory like that:
app.factory('FoobarServices', ['$http', function ($http) {
var Foobar = {
// Model
};
return {
getFoobar: function () {
},
setFoobar: function (Foobar) {
},
update: function (foobar) {
},
delete: function (id)
}
};
}]);
Or something like:
app.factory('Fooba', ['$http', function($http) {
function Foobar(foobar) {
// Initialize foobar
};
Foobar.prototype = {
getFoobars: function() {
},
setFoobar: function(foobar) {
},
update: function(foobar) {
},
delete: function(id) {
},
};
return Foobar;
}]);
I'm not sure to understand what's the pros and cons of each pattern, and which one is more suitable for an angular project.
Could you please tell me which one should I use?
It depends on how you want to use your service.
Factory is usually being used to store some constructor from which you can later instantiate some objects.
For example:
app.factory('Client', function () {
function Client (name) {
this.name = name;
}
Client.prototype.sayHello = function () {
console.log('Hello, my name is ' + this.name + '!');
}
return Client;
})
.controller('ClientController', function (Client) {
var bob = new Client('Bob');
})
If your service is singleton, you can register it as service instead of factory and angular will create an instance for you.
Or you can register it as factory but return some object with methods. It is useful when you don't want to deal with context (this) inside your service logic:
app.factory('ClientStorage', function () {
function set () {
// to be implemented
}
function get () {
// to be implemented
}
return {
get: get,
set: set
};
})

convert existing javascript file for requirejs

I had a javascript file like below..
First, I have some functions defined, and call the function on some event (document.ready here)
function foo(arg) {
return arg;
}
function bar(arg) {
return arg;
}
$(document).ready(function(){
doSomething();
});
Now I am trying to use requirejs and having trouble figuring out how to modify this file for it.
You can try this approach:
define(['dep'], function (dep) { //If you have any dependency
function foo(arg) {
return arg;
}
function bar(arg) {
return arg;
}
return {
myMethods: {
bar: bar(arg),
foo: foo(arg)
}
};
});
You shouldn't include document.ready here. Instead use that where you are going to use this module as a dependency.
This module will return myMethods object containing your methods.
Let's say you would have two files, main.js, which contains the initial call to require, and code.js, which contains the code. What you can do is this:
in main.js
$(function () {
require([
"/Url_To_Code.JS_Here"
], function (
code) {
code.doSomething();
});
});
in code.js:
define(
[],
function () {
var foo = function () {
};
var doSomething = function () {
};
return {
doSomething : doSomething
};
}
);
so whatever you export from code.js (what is returned), you can access in main.js

How to bind dynamic function to dynamic event

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 }
});

Variable Scope: cross-class function call

I have a vehicle and a product object and I need vehicle to call a function within product.... I can't seem to figure it out, what should I do here?
var vehicle = function () {
return {
init: function () {
var that = this;
jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
e.preventDefault();
that.remove(jQuery(e.currentTarget).parents('.vehicle-year-profile'));
});
jQuery('.vehicle-year-profile .options .edit').bind('click', function (e) {
e.preventDefault();
that.edit(jQuery(e.currentTarget).parents('.vehicle-year-profile').attr('id'));
});
jQuery('#association-detail .save').bind('click', function (e) {
e.preventDefault();
that.save();
});
},
edit: function (id) {},
save: function () {},
remove: function (el) {},
reset: function () {}
}
}();
var product = function () {
return {
refreshHistory: function () {}
};
}();
Have you tried
product.refreshHistory();
?? The variable "product" is global (or at least relatively global), so code inside the "vehicle" object can refer to it directly.

Categories