how to call the function knockout - javascript

var ViewModel = function(){
var self = this;
self.Check = function(){
alert('ok');
}
};
$(function () {
ko.applyBindings(new ViewModel());
});
** how to call a function Check() in normal script from knockout**

Just keep a reference to your view model:
var myVM = new ViewModel();
ko.applyBindings(myVM);
Now you can call the function:
myVM.Check();
But if you want to be able to use it outside the doc ready, you'll need to return it from there and assign it to a variable, or use a global variable.
So you could do something like this:
var myVM = new ViewModel();
$(function() {
ko.applyBindings(myVM);
});
//...
myVM.Check();
If you wanted to use this function as an event handler (for example, to handle a click) you'd do something like this (in HTML):
<a data-bind="click: Check">Click me to check!</a>
For other events, you'd use the event binding.

If you want to bind it to a function do this:
js:
var ViewModel = function(){
var self = this;
self.Check = function(){
return "Ok";
}
};
$(function () {
ko.applyBindings(new ViewModel());
});|
markup
<span data-bind="text:Check()" />
See fiddle:
http://jsfiddle.net/P4bP7/

Related

Undefined $(this) on nested functions

So basically I have two functions on my click() trigger.
var firstFunction = function() {
var id = $(this).attr('id');
alert(id);
};
var secondFunction = function() {
//something here
};
$('#trigger').click(function() {
firstFunction();
secondFunction();
});
On firstFunction() I'm trying to get $(this).attr('id') but it's returning undefined.
I know it has something two do with calling multiple functions because it works when I only call one function
$('#trigger').click(firstFunction);
Sample Fiddle here
As per your existing approach this refers to Window object not the element which invoke the event.
You can use .bind()
The bind() method creates a new function that, when called, has its this keyword set to the provided value,
$('#trigger').click(function() {
firstFunction.bind(this)();
secondFunction.bind(this)();
})
var firstFunction = function() {
var id = $(this).attr('id');
console.log(id);
};
var secondFunction = function() {
//something here
var id = $(this).attr('id');
console.log(id);
};
$('#trigger').click(function() {
firstFunction.bind(this)();
secondFunction.bind(this)();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="trigger">Click Me</button>
Fiddle
It's returning undefined because you aren't applying the same this as the event. You can achieve this by using call or apply instead of calling it directly.
$('#trigger').click(function() {
firstFunction.call(this);
secondFunction.call(this);
});
The this inside the firstFunction will be the window object itself - pass this to the function to fix it - see demo below:
var firstFunction = function(el) {
var id = $(el).attr('id');
alert(id);
};
var secondFunction = function() {
//something here
};
$('#trigger').click(function() {
firstFunction(this);
secondFunction(this);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="trigger">Click Me</button>
Another way is to use Function.prototype.call to bind a this argument to the funciton:
var firstFunction = function() {
var id = $(this).attr('id');
alert(id);
};
var secondFunction = function() {
//something here
};
$('#trigger').click(function() {
firstFunction.call(this);
secondFunction.call(this);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="trigger">Click Me</button>
You can pass the jQuery object element and than only use it in your function:
var firstFunction = function($el) {
var id = $el.attr('id');
console.log(id);
};
var secondFunction = function() {
//something here
};
$('#trigger').click(function() {
firstFunction($(this));
secondFunction();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="trigger">Button</button>
click() handler receives event as parameter. Pass it because this is not available in the scope of firstFunction().
Like this:
var firstFunction = function(target) {
var id = $(target).attr('id');
alert(id);
};
var secondFunction = function() {
//something here
};
$('#trigger').click(function(e) {
firstFunction(e.target);
secondFunction();
});
Nothing to do major, it's quite simple.
If you are calling a function and into that function you need an event to be used, then pass a reference in the function parameter.
I have updated the code in your Fiddle and updated with Mine:
Step 1:
$('#trigger').click(function(event) {
var that = this;
firstFunction(that);
secondFunction(that);
});
Created a variable that assigned this to that and passed into function parameter.
Note that, writing event in the click function is required to define this as a local click reference (Not a window)
Step 2:
Passed that rather than this, to make sure the reference is from click function only not of window.
var firstFunction = function(that) {
var id = $(that).attr('id');
alert(id);
};
Updated Fiddle

Mootools Class to Jquery

I'm converting a mootools class to Jquery, but I'm with a problem at the moment.
I've the following code (mootools)
var ListaItens = new Class({
...
...
initialize: function(element){
....
this.btnAdd = this.tabela.getElement('.add_linha button');
if(this.btnAdd){
this.btnAdd.addEvent('click', this.addLinha.bindWithEvent(this));
this.checkAdd();
}
...
},
addLinha: function(){
}
});
Now in Jquery I've this
var ListaItens = function(element, maxLinhas){
...
this.btnAdd = this.tabela.find('.add_linha button')[0];
if(this.btnAdd){
//$(this.btnAdd).proxy('click', this.addLinha);
$(this.btnAdd).on("click", this.addLinha);
this.checkAdd;
}
...
this.addLinha = function(){
}
})
My problem is how to bind the addline function to btnAdd. My code isn't work because the element 'this' change. And I don't know how to convert the function bindWithEvent to jquery.
Any solution?
Thanks in advance
As far as I know, jQuery does not provide a similar concept of classes as mootools does, so one thing you can do is to use the »classic JS approach« to create classes like so:
function ListaItens () {
var that = this;
this.tabela = $(…);
this.btnAdd = this.tabela.find(…);
if (this.btnAdd) {
this.this.btnAdd.on('click', function (e) {
that.addLinha();
})
}
}
ListaItens.prototype.addLinha = function () {
}
var instance = new ListaItens();
So, to answer your question: What you basically need to do is to keep a reference to the »original this«

jQuery - Trigger a function

I am trying to trigger a function from a html file that is located in another function in js file. I am trying to use the trigger method but i cannot make it to work.
Any suggestions how to do this? FIDDLE
<div id="result4" style="color:white; background:black">
from function
</div>
<script>
var TEST = new test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.trigger('reset');
</script>
JS
function test(args) {
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
}
Looking at the console log, your fiddle has an error:
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
$this is not defined.
and looking at the documentation for trigger:
http://api.jquery.com/trigger/
you are invoking it wrong. You are creating your own object that does not have a trigger method.
You need to define $this and return it as the object for test since trigger is a jquery function and not a native JavaScript Object function.
function test(args) {
var $this = $(this); // declare $this
var default_options = {
breakingPoint: 2000
};
var options = $.extend({}, default_options, args);
$("#result1").html(options.type);
$("#result2").html(options.file);
$("#result3").html(options.breakingPoint);
$this.on('reset', function() {
$("#result4").html("new text");
console.log("OK");
});
return $this;
}
var TEST = new test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.trigger('reset');
Wrap you tag code in jquerys ready event. This will execute it once the DOM is loaded instead of as it is parsed.
Maybe this is what you're looking for:
<script>
$(document).ready(function(){
var TEST = test({
type: "image",
file: "test.jpg",
breakingPoint: 100
});
TEST.reset();
});
</script>
In JS File
var test = function(options){
var that = {};
// you can use type, file & breaking point with option.type options.file etc..
that.reset = function() {
$("#result4").html("new text");
console.log("OK");
};
return that;
};

How bind a event and use apply/call to change the scope

+function ($) {
'use strict';
var popup = {
init: function(element) {
this._active = 'products__popup--active';
this._product = $('.products__popup');
this._element = $('[data-popup-to]');
this._TIME = 500;
popup.attachEvt();
},
attachEvt: function() {
var that = this;
that._element.bind('click', popup.handlerEvt.call(that));
},
handlerEvt: function() {
console.log(this);
console.log('test');
}
};
$(window).on('load', function() {
popup.init();
});
}(jQuery);
I have this script, and is not working yet, I cant show you a working example because it is not ready, I'm organizing the code first.
And there is a problem with the attachEvt function, inside it I want to call another function of my object, this function will bind a click in the that._element, but I want pass to the handlerEvt the scope of this (the clicked element) and the that (the object), but this is not working:
that._element.bind('click', popup.handlerEvt.call(that));
I'm just passing the that scope and when the script loads, the element will be clicked without click, I want avoid this.. this is possible?
UPDATE:
Resuming:
I want be able to use the scope of the object (that) and the scope of the clicked element (this) inside the handlerEvt function, but without make the event click when the script loads.. :B
Try utilizing .bind() , with this set to that._element , that passed as parameter to handlerEvent . Note order of parameters at handlerEvent: obj: that first , evt event object second
+function ($) {
'use strict';
var popup = {
init: function(element) {
this._active = 'products__popup--active';
this._product = $('.products__popup');
this._element = $('[data-popup-to]');
this._TIME = 500;
popup.attachEvt();
},
attachEvt: function() {
var that = this;
that._element.bind('click', popup.handlerEvt.bind(that._element, that));
},
handlerEvt: function(obj, evt) {
console.log(evt, obj, this);
console.log('test');
}
};
$(window).on('load', function() {
popup.init();
});
}(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-popup-to="true">click</div>

Events in Backbone.js

Can u help with the click event?? here is my code.
$(function() {
var Trainee = Backbone.Model.extend();
var TraineeColl = Backbone.Collection.extend({
model: Trainee,
url: 'name.json'
});
var TraineeView = Backbone.View.extend({
el: "#area",
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(trainee){
var areaTemplate = this.template(trainee.toJSON());
$(this.el).append(areaTemplate);
},this);
return this;
}
});
var trainee = new TraineeColl();
var traineeView = new TraineeView({model: trainee});
trainee.fetch();
trainee.bind('reset', function () {
traineeView.render();
});
});
my o/p after(trainee.toJSON) is
Sinduja
E808514
HPS
Shalini
E808130
HBS
Priya
E808515
HSG
Everything is fine with the o/p...
Now i want to get this o/p oly after a button click....
Simply add an event to that button. Since you're using jQuery, that should be simple :
$(function () {
$("#your_button_id").on("click", function (e) {
e.preventDefault();
// your code here
});
});
I don't understand what the o/p is...
Anyway, you can do something like that :
trainee.bind('reset', function () {
$('button').click(function() {
traineeView.render();
});
});
with the proper jQuery selector $('button') for your button...

Categories