0

I set jQuery object's data using a function:

oTabSearch.data('search_data', collect_data());

Is there a way to somehow recalculate this data piece e.g. if I get data from object:

var search_data = oTabSearch.data('search_data');

it would first set 'search_data' data using collect_data() function and then return it?

5
  • Do you mean, do both lines in one line, or every time you request .data('search_data') it runs collect_data Commented Jan 28, 2013 at 16:38
  • No, pls read api.jquery.com/data Commented Jan 28, 2013 at 16:38
  • Just to clarify what you are asking, do you want the "search_data" data item to be calculated on-the-fly whenever it is requested? Commented Jan 28, 2013 at 16:38
  • 1
    I don't get it, does'nt it already do this ? -> FIDDLE, and what would be the point of storing something in data, if the function runs and the data is recalculated everytime, would'nt it be easier to just run the function directly? Commented Jan 28, 2013 at 16:42
  • adeneo, This approach allow me to assign different search criteria to each tab so that I can get data for search in one place and specific way like this: $(this).data('callback')($(this).data('search_data')()); I set the data in one place and if something will change I can easily edit the data settings in one place. This is very convenient approach in my opinion. Do you have any better ideas of doing that? Commented Jan 28, 2013 at 16:57

1 Answer 1

2

You can do this...

oTabSearch.data('search_data', collect_data);  // notice no parenthesis

and to run the function...

var search_data = oTabSearch.data('search_data')();  // notice the empty parenthesis

That effectively stores a copy of the function as a data object and then runs it again when you request. It does not store any return value.

Here's an example jsFiddle...

http://jsfiddle.net/Tr3zK/

Click "mydiv" to see the data value, therefore calling the function again.

Sign up to request clarification or add additional context in comments.

1 Comment

I rejected the edit because it was exactly the same as my suggestion, but you passed an anonymous function into data, rather than a function name. Other than that it was exactly the same thing. Glad you got it working :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.