Best practices with Ember ArrayProxy - ember.js

Ember's Em.ArrayProxy and Em.Array have many programatic methods available for notifying observers of changes to content. For example:
arrayContentDidChange
arrayContentWillChange
enumerableContentDidChange
enumerableContentWillChange
contentArrayWillChange
Em.ArrayProxy also has several methods for manipulating the ArrayProxy's content. For example:
this.pushObject('something random');
// Or
this.insertAt(2, 'something random');
When using the latter methods, does one have to use them in conjunction with the former methods? It seems silly that Ember's usually-automated property observers would require a manual kick here but I don't find the documentation very clear.

No, you don't have to use any methods in conjunction.
If you want to add items to your ArrayProxy, simply pushObject(). You would know this by just using the method and seeing that it just works.
From the docs:
This mixin implements Observer-friendly Array-like behavior. It is not a concrete implementation, but it can be used up by other classes that want to appear like arrays.
http://emberjs.com/api/classes/Ember.Array.html
Ember.Array is a type of class that in other programming languages (without mixins) receives the name of an interface.
An ArrayProxy wraps any other object that implements Ember.Array
http://emberjs.com/api/classes/Ember.ArrayProxy.html
Ember.ArrayProxy is exactly what the name says, a proxy, that wraps around any object that has implemented the Ember.Array interface.
The other methods, that you mention, might be implemented/overridden if you are making your own "subclass" of Ember.Array. Some must be implement to make your subclass ArrayProxy friendly. Or if you want to add custom behaviour, maybe write to a log whenever arrayContentDidChange, then you override that method and add whatever logic your app needs.
That is Object Oriented Programming and all those explanations are out of scope for the documentation of any framework.

Are you asking whether pushObject et cetera trigger those events?
From the documentation for insertAt:
This will use the primitive replace() method to insert an object at the specified index.
From the documentation for replace:
You should also call this.enumerableContentDidChange()
So, yes, a properly implemented ArrayProxy will trigger those events when you add or remove things.

Related

Creating a "Publisher->Dispatcher->Subscriber" pattern event system?

Edit: TL;DR
I guess my main problem is I don't know how to store a list of functions that all take one argument, where the argument type is different between each function, but always extends from EventBase, for calling later.
i.e: EventChild extends from EventBase. A function with the signature
<void (EventChild&)>
will not fit into a variable of type
std::function<void(EventBase&)>
How do I store functions like this, knowing that a user shouldn't have to modify the class where they are stored each time they create a new event extending from our EventBase class?
Note: I had previously been told I could use a dynamic_cast to accomplish this. I have been trying to do exactly that, but it hasn't been working. I imagine for that to work I would have to use pointers somehow, but I am new enough to C++ that I'm not sure how to do it. Maybe that should be the starting point?
One of the problems with dynamic casting pointers I have been having is 'I can convert a pointer of type:
(Subbscriber*)(getDemoEvent(EventDemo&)
to type:
void(EventBase&)
or something along those lines. (not at my computer right now to try it)
This is obviously a problem limited to member functions, I assume.
I recently posted a question on here with the intention of solving an issue for a C++ Event system based on a "Publisher->Dispatcher->Subscriber" pattern. I don't know the exact name of this pattern, but I hear that it is a variant on the Observer pattern with an added "middle-man."
I have been trying to get this system to work for a while now and I am completely stuck. It was suggested in the comments of the previous question that for what I was trying to accomplish, my program layout is incorrect. This is very likely the case since I had been researching other event systems that were close to what I am after trying to modify them for use they were unintended for. So I figured I would describe what I am after, and ask the more general question of "How would you go about structuring and creating this?"
So here is my general idea of how the system should be laid out and how it should operate in a basic example:
Starting with the idea of 5 different files (plus headers and maybe some subclasses):
main.cpp
dispatcher.cpp
publisher.cpp
subscriber.cpp
eventbase.cpp
publishers and subscribers could be anything, and they only serve as an example here.
The first order of business would be to create an instance of our Dispatcher class.
Following that, we create instances of our publisher/subscriber classes. These 2 classes could be a part of the same file, different files, multiples of each, or not event be classes at all but simply free functions. For the sake of simplicity and testing, they are 2 separate classes that know nothing about each other.
When these 2 classes are created, they should be passed a reference or pointer to our dispatcher instance.
This is easy enough. Now let's get to how you should use the system.
A user of the system should be able to create a class that inherits from our EventBase class. Ideally, there should be no requirement on variables or functions to override from the base class.
Let's say we have created a new event class called EventDemo, with a public const char* demoString = "I am a Demo Event";.
From our subscriber class, we should be able to tell our dispatcher that we want to listen for and receive some events. The syntax for doing so should be as simple as possible.
Lets create a member function in our subscriber that looks like this:
void Subscriber::getDemoEvent(const EventDemo &ev) {
std::cout << ev.demoString;
}
Now we need a way to bind that member function to our dispatcher. We should probably do that in our constructor. Let's say that the reference to our dispatcher that we passed to our subscriber when we created it is just called 'dispatcher'.
The syntax for subscribing to an event should look something like this:
dispatcher->subscribe("EventToSubTo", &getDemoEvent);
Now since we are in a class trying to pass a member function, this probably isn't possible, but it would work for free functions.
For member functions we will probably need and override that looks like this:
dispatcher->subscribe("EventToSubTo", &Subscriber::getDemoEvent, this);
We use 'this' since we are inside the subscribers constructor. Otherwise, we could use a reference to our subscriber.
Notice that I am simply using a string (or const char* in c++ terms) as my "Event Key". This is on purpose, so that you could use the same event "type" for multiple events. I.E: EventDemo() can be sent to keys "Event1" and "Event2".
Now we need to send an event. This can be done anywhere we have a reference to our dispatcher. In this case, somewhere in our publisher class.
The syntax should look something like this to send our EventDemo:
dispatcher->emit("EventToSubTo", EventDemo());
Super simple. It's worth noting that we should be able to assign data to our event through it's constructor, or even template the event. Both of these cases are only valid if the event created by the user supports it.
In this case, the above code would look something like this:
dispatcher->emit("EventToSubTo", EventDemo(42));
or
dispatcher->emit("EventToSubTo", EventDemo<float>(3.14159f));
It would be up to the user to create a member function to retrieve the data.
OK, so, all of that should seem pretty simple, and in fact, it is, except for one small gotcha. There are already systems out there that store functions in a map with a type of .
And therein lies the problem...
We can store our listener functions, as long as they accept a type of EventBase as their argument. We would then have to type cast that argument to the type of event we are after. That's not overly difficult to do, but that's not really the point. The point is can it be better.
Another solution that was brought up before was the idea of having a separate map, or vector, for each type of event. That's not bad either, but would require the user to either modify the dispatcher class (which would be hard to do when this is a library), or somehow tell the dispatcher to "create this set of maps" at compile time. That would also make event templating a nightmare.
So, the overly generalized question: How do we do that?
That was probably a very long winded explanation for something seemingly simple, but maybe someone will come along not not know about it.
I am very interested to hear thoughts on this. The core idea is that I don't want the 2 communicators (publisher and subscriber) to have to know anything about each other (no pointers or references), but still be able to pass arbitrary data from one to the other. Most implementations I have seen (signals and slots) require that there be some reference to each other. Creating a "middle-man" interface feels much more flexible.
Thank you for your time.
For reference to my last question with code examples of what I have so far:
Store a function with arbitrary arguments and placeholders in a class and call it later
I have more samples I could post, but I think it's highly likely that the structure of the system will have to change. Waiting to hear thoughts!

Famo.us: different ways of creating and calling functions

Hoping someone can provide an explain-like-I’m-five elucidation of the difference between the following types of functions within Famo.us, and when it’s appropriate to use them:
sampleFunction() {}
_sampleFunction() {}
SampleView.prototype.sampleFunction() {}
.bind and .call are also thrown around a lot…I understand them vaguely but not as concretely as I’d like. That might be a different question, but please feel free to use them in your explanation!
Apologies for the vagueness...wish there was more regarding this in famo.us university.
None of what you're looking at is syntax specific to Famo.us. It's actually common, if intermediate level, VanillaJS.
The _ is simply a coding convention to denote that a specific function should belong to the parent scope (ie a member/private function, whatever you prefer to call it). Javascript doesn't really have support for encapsulation - the act of blocking other classes and objects from accessing another class's functions and variables. While it is possible, it's quite cumbersome and hacky.
You'll see that Famo.us uses the underscore convention to denote that a function is a member of the class using it. Some of these functions are actually just aliases to the actual Javascript native function, for example ._add actually just call's Javascript's .add method. Of course, ._add could be updated in the future on Famo.us's end to do more in the future if that's required. You really wouldn't want to try and write over the native Javascript add. That's super bad.
The other upshot is that you can document that class and say that you can and should use the _add method for a specific purpose/scenario. You'll see that in the API docs.
Understanding prototype is a core part of what it means to be a Javascript Programmer, after all, it is a prototype driven language. MDN has a much better explanation than anything I can offer here but it's basically at the core of your classes.
If you want to extend off of an existing class (say, create your own View or Surface type) you would extend it's prototype. Check out Famous Starter Kit's App examples and see how many of them create an "AppView" class, which takes the prototype of the core View, copies it for itself, and then adds it's own functions, thus extending View without ruining the original copy.

c++ GUI Events/Messaging Design

So, I'm making a simple game using DirectX 9 and C++. I looked at the SDK's GUI, but I think I can implement something simpler.
All I want are windows, labels, buttons, textboxes, and checkboxes.
I've created a base class GUIObject, that all inherit from. It includes basics like size and focus and whatnot. Then the derived classes, GUILabel for example, all define render(), update() and whatnot.
My question is how to handle events, like clicks? I had it working with GUILabel::Click() defining every possibility based on the current instance's text member value. It felt wrong and I realized that every single label that needed to be clicked would have to be defined in the GUILabel class. I'd like to move that to each game state's code.
So, I briefly tried making the GUILabel::Click() take a function pointer as an argument. But then I realized I needed to have the state's class member method as static (not really possible, unless everything in it is static as well, right?) or also pass it a GUIObject class as well. Is that the way to go?
Could I define a derivation of GUILabel (or button, or whatnot) within a game state and just override whichever actions I needed? And then do that for whatever controls I need in that state?
What is the proper way to implement event handling?
You might want to look into using a signaling library such as boost::signals to allow you the flexibility of defining the interface between your GUI objects and the underlying events that each callback will trigger. It can also come in handy for the reverse relationship where you need GUI elements such as status indicators, etc. to respond to underlying events.
For callbacks/click events i would go with boost::function/boost::bind.
In my GUI framework I used to have two different abstract classes InputHandler and Renderable for handling touches and rendering. This leads to a design where components which don't need to be clickable (like UILabel) wont need to implement useless methods.
HTH,
Alex

is DISPID_VALUE reliable for invokes on IDispatchs from scripts?

Continuing from this question, i am confused whether DISPID_VALUE on IDispatch::Invoke() for script functions and properties (JavaScript in my case) can be considered standard and reliable for invoking the actual function that is represented by the IDispatch?
If yes, is that mentioned anywhere in MSDN?
Please note that the question is about if that behaviour can be expected, not what some interfaces i can't know in advance might look like.
A simple use case would be:
// usage in JavaScript
myObject.attachEvent("TestEvent", function() { alert("rhubarb"); });
// handler in ActiveX, MyObject::attachEvent(), C++
incomingDispatch->Invoke(DISPID_VALUE, IID_NULL, LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD, par, res, ex, err);
edit: tried to clarify the question.
It should be reliable for invokes on objects from scripts if the script defines it consistently. This should be the case for JScript/Javascript in MSHTML, but unfortunately there is really sparse documentation on the subject, I don't have any solid proof in-hand.
In my own experience, a Javascript function passed to attachEvent() should always be consistent- an object received that is a 'function' can only have one callable method that matches itself. Hence the default method is the only one you can find, with DISPID 0. Javascript functions don't ordinarily have member functions, although i'm sure there is a way for this to be possible. If it did have member functions, you would see them the same way as member functions on objects. Member functions in JScript will always be consistent with regard to IDispatchEx, according to the rules of expando functions, as any functions added to an object count as expandos.
IDispatchEx interface # MSDN
The default method or property that DISPID_VALUE invokes should be consistent for a given interface. That method/property has to be specified as DISPID_VALUE in the definition of the interface in the IDL for the type library. The only way it could change is if the owner of the interface released a new version of the interface that changed which method/property was the default but that would violate a fundamental rule of COM interfaces.
As meklarian said, DISPID_VALUE (0) seems to work pretty consistantly for JS functions (thus it works great with a custom attachEvent). I've been using them this way for about a year, and it's always worked. I've also found with an activeX control embedded with an <object> tag that to get it to work consistently, I need to implement IConnectionPointContainer and IConnectionPoint for the main (object tag) IDispatch-implementing CComObject, but any others that I expose to javascript as return values from methods or properties (through Invoke) I have to implement attachEvent and detachEvent myself.
When using Connection Points, the IDispatch objects in question will expect events to be fired to the same DISPID as they are attached to on your IDispatch object..
see http://code.google.com/p/firebreath/source/browse/src/ActiveXPlugin/JSAPI_IDispatchEx.h for an example of implementing the ConnectionPoints.
You can add DISPID's to a DISPINTERFACE, but you cannot change them once it has been published. If you need to, you can use IDispatch::GetIDsOfNames to map names to DISPIDs.
Pick up a copy of Inside Ole (2nd ed) and Inside Ole 2 (2nd ed) for a few bucks used on Amazon. It's a good reference for these obscure OLE incantations.

Extending an existing class like a namespace (C++)?

I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.