How to bind this to a callback?

My previous question was a duplicate, I read the answer from the post it duplicated but no luck.

I've added in a bind as suggested in the answers in the SO post. But I am still getting undefined.

I have a series of promises, before each execution, I check whether the user has cancelled the promise chain.

My issue is, I cannot access 'this' inside the call back methods, a crude example is below, I cannot access the p.test variable inside getMoreData()

p.test = 'hello!'; p.init = function(){ var self = this; this.getData() .then(function(data) { return self.shouldContinue(getMoreData,data).bind(self); }); } p.shouldContinue = function(cb, data) { // ... this.currentRequest = cb.call(this,data); }; p.getData = function(){ // return ajax call }; p.getMoreData = function(){ console.log(this.test); // undefined // return ajax call };

-------------Problems Reply------------

Did you try this?
You need to bind this into the cb

p.test = 'hello!';

p.init = function(){
var self = this;
this.getData()
.then(function(data) {
return self.shouldContinue(getMoreData,data).bind(self);
})
}

p.shouldContinue = function(cb, data){
...
this.currentRequest = cb(this,data).bind(this);
};

p.getData = function(){
//return ajax call
};

p.getMoreData = function(){
console.log(this.test); //undefined
//return ajax call
};

Change to this:

p.init = function(){
var self = this;

this.getData()
.then(function(data) {
return self.shouldContinue.bind(self, self.getMoreData, data)();
});
}

  1. bind self.shouldContinue to self and give it appropriate param.

  2. .bind returns a Function, so, you need to call it.So the self.shouldContinue will continues to call self.getMoreData, otherwise it left there waiting to be called.

return self.shouldContinue(getMoreData,data).bind(self);

It looks like you're accidentally calling shouldContinue, and trying to bind its result, rather than binding the function without calling it. This should get you what you need.

return self.shouldContinue.bind(self, self.getMoreData, data);

Remember that getMoreData is a function that's not defined under variable scope, so it needs to be accessed with a .

EDIT: Also noticed shouldContinue has a similar issue, but I'm confused by the intent of some parts of your code so I've added a comment to ask for more information.

Category:javascript Views:3 Time:2019-01-06

Related post

  • How to bind "this" for jQuery callbacks? 2009-08-07

    I am trying to set up a callback in jQuery that correctly binds "this" to the calling object. Specifically, here is the code I am working with. I am doing an ajax call in a Object like this: Object.prototype.doAjaxCall = function(url) { $.get(url, nu

  • How to bind this collection to my listbox 2011-09-29

    How do i wrap a collection of wrapped class. I have a property in my View Model which is of type AsyncVirtualizingCollection<Item> ItemValues{get;set;} Where Wrapper is a generic type Wrapper<T> Of Item class. Basically I am trying to do

  • How to bind enter key to callback in Javascript without slowing down the typing? 2012-04-05

    I need this for a chat box. When the user press enter, I want to trigger a callback (to send the message and clean the input field) So far I got this, but the typing becomes slow: $('#chat_input').keydown(function(event) { if(event.keyCode == '13') {

  • How to bind this function to input focus 2011-07-13

    I have the following simplified function. Real usage removed. So, onfocus I expect the value of the textbox to be alerted. I would like to keep the function definition separate from the usage. new function ($) { $.fn.setFocus = function () { alert($(

  • how to bind the converted value from a datatable to my gridview 2010-04-03

    how to bind the value to gridview i have a datatable DataTable dtBindGrid = new DataTable(); dtBindGrid = serviceobj.SelectExamTimeTable(txtSchoolName.Text, txtBranchName.Text, txtClass.Text, txtExamName.Text); foreach (DataRow row in dtBindGrid.Rows

  • Passing $(this) to a callback in jQuery? 2011-02-23

    I have two effects that I want to run one after another, but I can't work out how to pass $(this) to the callback from the first effect. This is what I have at the moment: if($(this).hasClass('flag')) { $('someElement').slideUp(); $(this).slideDown()

  • How to bind an indexer to a GridViewColumn in WPF? 2011-03-02

    In my ViewModel object I have a this indexer like: public bool this[enum effectType] { get { return CheckList.First ( e => e.EffectType == effectType ).IsChecked; } } but not sure how to bind this in Xaml. I have tried these: <GridViewColumn

  • How to bind an image to a Button in code behind? 2011-03-22

    I have a default WPF button and a image, separated distance apart. When I hover or press the button, the button gets the standard blue or grey effect. What I want to achieve is, when I hover or press the image, I would also get the same hover and pre

  • how to bind hash table to gridview 2011-09-29

    hi i have a hash table with following set of values int ID 1 string Name ram list date 2/3/2011 5/3/2011 Code: <asp:TemplateField HeaderText="ID"> <ItemStyle Width="200px"> </ItemStyle> <ItemTemplate> <asp:Label ID="lblID"

  • How to bind dynamic data from the database to the Datagrid ? 2011-10-20

    I am reading dynamic data from the MySQL using JSP and it's forwarding the details in the form of XML to the Flex. I would like to bind this XML data to the datagrid. Am able to bind the data if the datagrid has only one column but don't know how to

  • How to bind crystal report to manually created DataSet 2011-12-01

    I wan't to create DataSet from code and set it as data source for crystal report. I don't want to create a DataSet xsd file in VS if I don't have to. Just pure code. DataSet ds = new DataSet(); DataTable tbl = new DataTable(); DataColumn cln = new Da

  • How to bind a resource to a flowdocumentreader from a treeview with only XAML? 2011-12-20

    This time I am working on a help-window mini-application (to include in the other project, the imageediting application). I have a grid with two columns and a gridsplitter inbetween. On the left I have a treeview with several nodes (set in XAML) and

  • jQuery: How to deal with 'this' in AJAX callbacks 2010-05-24

    I currently have code similar to this for a form: $('#some-form') .submit(function() { // Make sure we are not already busy if($(this).data('busy')) return false; $(this).data('busy', true); // Do post $.post("some/url", $(this).serialize(), function

  • Multiple values in callback function from handler. How to bind these values sepretly 2012-03-01

    Like handler return these to values.. (ds) as data-set context.Response.Write(ds.Tables[0].Rows[0]["name"]); context.Response.Write(ds.Tables[0].Rows[1]["age"]); then how to bind them or find values secretly. for a single value i use function callbac

  • WPF C# how to create THIS binding in code? 2010-03-15

    I wonder, how to create this binding, since Line.X2 IS NOT dependency property! :( <Line Y1="0" X1="0" Y2="0" Stroke="Blue" StrokeThickness="3" Margin="0 -2 0 -2" X2="{Binding Path=RenderSize.Width, RelativeSource={RelativeSource FindAncestor, Anc

  • How do I bind this data to a DataGrid? 2010-12-15

    I've got a TreeView, and each TreeViewNode has an object in its Tag property. When a node in the treeview is selected, I want a DataGrid to be populated with the name and value of all the fields of the object, obtained through reflection. I can't fig

  • How to simply bind this to ConverterParameter? 2011-05-07

    I have problem and i don't know how to solve this simple, i have many points like this, then solution should be not complicated. I have main project with Settings and main XAML. I have dependency project with Binding Converter and XAML File looks lik

  • How can I pass "this" into setTimeout callback? 2011-06-06

    fiddle code: <button onclick="this.disabled=true; setTimeout(function(){this.disabled=false;},500);">click</button> this seems to refer to the window rather than the button. How can I pass the button object in so that I can re-enable it?

  • How to send "this" to named function in event binding statement? 2011-07-31

    Basically, i am bit stuck, dont know if its possible to turn $("#id").click(function(){ var that = jQuery(this); wildFunction(that); }); into $("#id").click(wildFunction(this)); --------------Solutions------------- "this" is a scope variable so it wo

  • how to bind a view to alertdialog and use the children in this view in android? 2012-02-20

    I have a View like this: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fil

  • Coffeescript timer and 'this' pointer on callback 2011-02-07

    I'm having a problem with what the browser considers 'this' to be. In the following example, calling pingMe() on abc will wait 1 second and then the browser will say that Object DOMWindow has no method 'func'. Instead of resolving 'this' to the insta

  • How to bind from a source property to a TARGET method 2011-02-08

    There are plenty of ways to bind a SOURCE method to target property, either by ValueConverter or by ObjectDataProvider. However, what if I want to have the binding affect the target METHOD? Consider the following example: class ListBoxViewModel { pub

  • Prototype code to jQuery ( bind(this) vs closures ) 2011-05-25

    Mornin' all. I'm rewriting a prototype code to a JQuery plugin and don't know how to handle this piece : this.observers = events.map(function(name) { var handler = this["on" + name.].bind(this); this.element.observe(name, handler); return { name: nam

  • Javascript bind "this" to event 2011-12-27

    Below is an error I am getting from binding "this" to a click event in javascript. The format of the js is Jaml/Mooml and may be unfamiliar to some but I assure you the syntax is proper. I have been binding "this" to many events in the same way and t

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.072 (s). 11 q(s)