up vote 0 down vote favorite

I like jQuery's ability to method chain commands ( .animate().css() etc ) which in the backend is achieved by returning the special variable "this".

How can I implement a similar method of chaining without having to set state within my object. Take for example:

that.getHospitalCoverDataStore().findBy('short_name').withValue('sam');

This method chain queries a field in the datastore "short_name" using the value "sam". I can set an internal state to "short_name" when the first method has been called then look that up again when withValue is called. This seems like a kludge to me though, for a start I can't throw an error if withValue is called before findBy as it will reuse the last findBy setting.

How can I better implement this?

link|flag

3 Answers

up vote 3 down vote accepted

You can make the findBy method return a different object, that encapsulates the datastore and the field name, and that has the withValue method:

function findBy(field) {
  return {
    dataStore: this,
    field: field,
    withValue: function(value) {
      // query the dataStore and return result
    }
  };
}
link|flag
Love it, this is what I was thinking so it's good to get some confirmation on it. – Samuel Sep 20 at 3:55
up vote 3 down vote

Your findBy method should return a separate object with a withValue method. (and perhaps startsWith, but no unrelated methods)

link|flag
up vote 0 down vote

Looks like findBy() could be implemented as a separate object with the method withValue(), it doesn't look like withValue() should be a method for the HospitalCoverDataStore.

link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.