Search Results

Search found 237 results on 10 pages for 'observer'.

Page 2/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • iPhone OS: KVO: Why is my Observer only getting notified at applicationDidfinishLaunching

    - by nickthedude
    I am basically trying to implement an achievement tracking setup in my app. I have a managedObjectModel class called StatTracker to keep track of all sorts of stats and I want my Achievement tracking class to be notified when those stats change so I can check them against a value and see if the user has earned an achievement. I've tried to impliment KVO and I think I'm pretty close to making it happen but the problem I'm running into is this: So in the appDelegate i have an Ivar for my Achievement tracker class, I attach it as an observer to a property value of my statTracker core data entity in the applicationDidFinishLaunching method. I know its making the connection because I've been able to trigger a UIAlert in my AchievementTracker instance, and I've put several log statements that should be triggered whenever the value on the StatTracker's property changes. the log statement appears only once at the application launch. I'm wondering if I'm missing something in the whole object lifecycle scheme of things, I just don't understand why the observer stops getting notified of changes after the applicationDidFinishLaunching method has run. Does it have something to do with the scope of the AchievementTracker reference or more likely the reference to my core data StatTracker is going away once that method finishes up. I guess I'm not sure the right place to place these if that is the case. Would love some help. Here is the code where I add the observer in my appDidFinishLaunching method: [[CoreDataSingleton sharedCoreDataSingleton] incrementStatTrackerStat:@"timesLaunched"]; achievementsObserver = [[AchievementTracker alloc] init]; StatTracker *object = nil; object = [[[CoreDataSingleton sharedCoreDataSingleton] getStatTracker] objectAtIndex:0]; NSLog(@"%@",[object description]); [[CoreDataSingleton sharedCoreDataSingleton] addObserver:achievementsObserver toStat:@"refreshCount"]; here is the code in my core data singleton: -(void) addObserver:(id)observer toStat:(NSString *) statToObserve { NSLog(@"observer added"); NSArray *array = [[NSArray alloc] init]; array = [self getStatTracker]; [[array objectAtIndex:0] addObserver:observer forKeyPath:statToObserve options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; } and my AchievementTracker: - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"achievemnt hit"); //NSLog("%@", [change description]); if ([keyPath isEqual:@"refreshCount"] && ((NSInteger)[change valueForKey:@"NSKeyValueObservingOptionOld"] == 60) ) { NSLog(@"achievemnt hit inside"); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"title" message:@"achievement unlocked" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:nil]; [alert show]; } }

    Read the article

  • Are Promises/A a good event design pattern to implement even in synchronous languages like PHP?

    - by Xeoncross
    I have always kept an eye out for event systems when writing code in scripting languages. Web applications have a history of allowing the user to add plugins and modules whenever needed. In most PHP systems you have a global/singleton event object which all interested parties tie into and wait to be alerted to changes. Event::on('event_name', $callback); Recently more patterns like the observer have been used for things like jQuery. $(el).on('event', callback); Even PHP now has built in classes for it. class Blog extends SplSubject { public function save() { $this->notify(); } } Anyway, the Promises/A proposal has caught my eye. It is designed for asynchronous systems, but I'm wondering if it is also a good design to implement now that even synchronous languages like PHP are changing. Combining Dependency Injection with Promises/A seems it might be the best combination for handling events currently.

    Read the article

  • Any way to add an observer to the head of the queue using Element#observe?

    - by Josh
    This might not be possible but before I rewrite part of my application I wanted to ask... I have a JavaScript app which creates a submit <input> and observes that input's click event using Prototype's Element#observe function. For a few particular pages on one particular site which uses this app, I need to apply some additional business logic before the code which executes normally when the button is clicked. Is there any way I can use Elemen#observe to add my new event handler before the existing event handler, so I can stop the event if these new conditions aren't met? If not I'll probably solve this the "proper" way by having the application fire a specific beforeTakingAction event and add a listener for that which prevents the application from taking it's action, but that's more complicated than this simple problem requires, and requires rewriting part of a shared application for just one user...

    Read the article

  • Designing web-based plugin systems correctly so they don't waste as many resources?

    - by Xeoncross
    Many CMS systems which rely on third parties for much of their code often build "plugin" or "hooks" systems to make it easy for developers to modify the codebase's actions without editing the core files. This usually means an Observer or Event design pattern. However, when you look at systems like wordpress you see that on every page they load some kind of bootstrap file from each of the plugin's folders to see if that plugin will need to run that request. Its this poor design that causes systems like wordpress to spend many extra MB's of memory loading and parsing unneeded items each page. Are there alternative ways to do this? I'm looking for ideas in building my own. For example, Is there a way to load all this once and then cache the results so that your system knows how to lazy-load plugins? In other words, the system loads a configuration file that specifies all the events that plugin wishes to tie into and then saves it for future requests? If that also performs poorly, then perhaps there is a special file-structure that could be used to make educated guesses about when certain plugins are unneeded to fullfil the request. Any ideas? If anyone wants an example of the "plugin" concept you can find one here.

    Read the article

  • Where to add an observer to the NotificationCenter in a UITableViewController

    - by Saifis
    I want to send a notification from a UITableViewController-A to UITableViewController-B. I was adding the observer in the initwithCoder of the UITableViewController that is supposed to catch the notifications. The classes are correlated as folows RootViewController ===NavigationController-A =====UITableViewController-A ===NavigationController-B =====UITableViewController-B I need to add the observer before the views are actually loaded because notifications may be sent before the view is called. However I have been told that initializing in the initWithCoder method in a UIViewController is not advisable, and was told to add the observer in the AppDelegate. Are there any other suggestions for doing this?

    Read the article

  • Store Observer not being called always

    - by Nixarn
    Has anyone else here experienced problems with their Store Observer class not being called always when the user for instance cancels a request (or purchases something) We just had our update that brought in app purchases go live last night, and before that we had obviously tested everything tons of times against the Sandbox and everything was working fine. Now however, when the update went live in a real environment we keep getting issues with the store. For instance, in a freshly booted iPhone / iPod, the first time you run the app, if you then try to make a purchase and then immediately cancel it from the first dialog, it seems as if the callback for the cancel is not getting called. If you then restart the app it seems as if it always works after that, or at least. Same thing with other callbacks, seems as if our store observer isn't listening as the callbacks aren't being registered on the phone. One example of this is if you purchase something, then nothing will happen (if this is the first time the app is launched at least). You get the purchase successful dialog from the app store but it seems as if our own code isn't called. If you then quit the app and restart it the callback gets called. Same problem happens if you for instance try to start a request to download all previous purchases and then immediately cancel it as the first dialog pops up, if you do that then the callback for a failed restore is not called, until you then restart the app and try it again, then it always seems to work. The way we have implemented our store observer is by creating a custom class that's implements the SKPaymentTransactionObserver interface. @interface StoreObserver : NSObject<SKPaymentTransactionObserver> In the class we have implemented the following methods: - (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions - (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue - (void)paymentQueue:(SKPaymentQueue *)queue restoreCompletedTransactionsFailedWithError:(NSError *)error The way our restore process works is that if you tap on the button that allows you to download all we simply run the restoreCompletedTransactions code as follows: [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; However, the callback, restoreCompletedTransactionsFailedWithError, which has been implemented in the store observer, does not always get called when we try to cancel the request. This happens when you boot the iPhone / iPod and try this for the first time. If you after that restart the app everything works fine. The StoreObserver class is created when our app is launched, just by running the following code: pStoreObserver = [[StoreObserver alloc] init]; [[SKPaymentQueue defaultQueue] addTransactionObserver:pStoreObserver]; Has anyone else had any similar experiences? Or does anyone have any suggestions on how to solve this? As I said, in the sandbox environment everything was working fine, no issues whatsoever, but now once it's gone live we're experiencing these.

    Read the article

  • Access functions from user control without events?

    - by BornToCode
    I have an application made with usercontrols and a function on main form that removes the previous user controls and shows the desired usercontrol centered and tweaked: public void DisplayControl(UserControl uControl) I find it much easier to make this function static or access this function by reference from the user control, like this: MainForm mainform_functions = (MainForm)Parent; mainform_functions.DisplayControl(uc_a); You probably think it's a sin to access a function in mainform, from the usercontrol, however, raising an event seems much more complex in such case - I'll give a simple example - let's say I raise an event from usercontrol_A to show usercontrol_B on mainform, so I write this: uc_a.show_uc_b+= (s,e) => { usercontrol_B uc_b = new usercontrol_B(); DisplayControl(uc_b); }; Now what if I want usercontrol_B to also have an event to show usercontrol_C? now it would look like this: uc_a.show_uc_b+= (s,e) => { usercontrol_B uc_b = new usercontrol_B(); DisplayControl(uc_b); uc_b.show_uc_c += (s2,e2) => {usercontrol_C uc_c = new usercontrol_C(); DisplayControl(uc_c);} }; THIS LOOKS AWFUL! The code is much simpler and readable when you actually access the function from the usercontrol itself, therefore I came to the conclusion that in such case it's not so terrible if I break the rules and not use events for such general function, I also think that a readable usercontrol that you need to make small adjustments for another app is preferable than a 100% 'generic' one which makes my code look like a pile of mud. What is your opinion? Am I mistaken?

    Read the article

  • Optimal communication pattern to update subscribers

    - by hpc
    What is the optimal way to update the subscriber's local model on changes C on a central model M? ( M + C - M_c) The update can be done by the following methods: Publish the updated model M_c to all subscribers. Drawback: if the model is big in contrast to the change it results in much more data to be communicated. Publish change C to all subscribes. The subscribers will then update their local model in the same way as the server does. Drawback: The client needs to know the business logic to update the model in the same way as the server. It must be assured that the subscribed model stays equal to the central model. Calculate the delta (or patch) of the change (M_c - M = D_c) and transfer the delta. Drawback: This requires that calculating and applying the delta (M + D_c = M_c) is an cheap/easy operation. If a client newly subscribes it must be initialized. This involves sending the current model M. So method 1 is always required. Think of playing chess as a concrete example: Subscribers send moves and want to see the latest chess board state. The server checks validity of the move and applies it to the chess board. The server can then send the updated chessboard (method 1) or just send the move (method 2) or send the delta (method 3): remove piece on field D4, put tower on field D8.

    Read the article

  • strategy for observer pattern?

    - by fayer
    I want to use observer pattern for a logging system. We have got logObservers and logObservables. The class that will have to log something will implement iLogObservable and include these methods: private $logObservers = array(); public function addLogObserver($logObserver) { $this->logObservers[] = $logObserver; } public function removeLogObserver($logObserver) { $this->logObservers[] = $logObserver; } public function write($type, $message) { foreach($this->logObservers as $logObserver) { $logObserver->log($level, $message); ; } } Then I noticed, that a lot of classes that will use logging will have these methods and I have to copy paste. So isn't it better to have these methods in a class I call LogObservable or just Log and then use strategy (instantiate this class inside all classes that will have to log). When I change the methods in Log, all logObservables will be affected. However, I have not seen anyone use observer pattern with strategy pattern yet, but it seems to be very efficient and remove the duplications. What do you think?

    Read the article

  • How do I synchronize GUI-Elements?

    - by anonymous2500
    Hello, I have a little problem with my java-program. I wanna use Observer, to synchronize two GUIs. But I can't synchronize the JComponent / JButton elements. For example: I have a GUI-Class which implements the Observer-Class: public class GUI extends JFrame implements Observer I have a second "GUI"-Class which extends the JButton-Class and makes changes on a specific Button-Element. public class Karte extends JButton{ ... this.setEnabled(false); ... How do I synchronize this Button via Observable? I have already tried to use "extends Observable" in this class, but the "setEnabled()" method is explicit for the JButton-Class, which is not Observable! Can someone help? Thanks.

    Read the article

  • Prototype function to set onclick event observer in checkboxes

    - by xain
    Hi, I want to set an observer for each of the following checkboxes: <div id="listr"> <ul id="lr" style="list-style-type: none"> <p class="tir">Text 1</p> <li class="ro"><input type="checkbox" name="r1" id="r1"/>A1</li> <li class="ro"><input type="checkbox" name="r2" />A2</li> <p class="tir">Text 2</p> <li class="rubro"><input type="checkbox" name="r3" />B1</li> <p class="tir">Text 3</p> <li class="ro"><input type="checkbox" name="r4" />B2</li> </ul> </div> It works if I write one observer per checkbox, but I want to do it in a short fashion, so I need something like $$('listr.lr.li.input').invoke('observe',click,function(field) { alert(this.name + ' clicked ' + this.checked); // other stuff ... }); Which is not working Thanks in advance

    Read the article

  • Magento - save quote_address on cart addAction using observer

    - by Byron
    I am writing a custom Magento module that gives rate quotes (based on an external API) on the product page. After I get the response on the product page, it adds some of the info from the response into the product view's form. The goal is to save the address (as well as some other things, but those can be in the session for now). The address needs to be saved to the quote, so that the checkout (onestepcheckout, free version) will automatically fill those values in (city, state, zip, country, shipping method [of which there are 3]) and load the rate quote via ajax (which it's already doing). I have gone about this by using an Observer, and watching for the cart events. I fill in the address and save it. When I end up on the cart page or checkout page ~4/5 times the data is lost, and the sql table shows that the quote_address is getting save with no address info, even though there is an explicit save. The observer method's I've used are: checkout_cart_update_item_complete checkout_cart_product_add_after The code saving is: (I've tried this with the address, quote and cart all not calling save() with the same results, as well as not calling setQuote() $quote->getShippingAddress() ->setCountryId($params['estimate_to_country']) ->setCity($params['estimate_to_city']) ->setPostcode($params['estimate_to_zip_code']) ->setRegionId($params['estimate_to_state_code']) ->setRegion($params['estimate_to_state']) ->setCollectShippingRates(true) ->setShippingMethod($params['carrier_method']) ->setQuote($quote) ->save(); $quote->getBillingAddress() ->setCountryId($params['estimate_to_country']) ->setCity($params['estimate_to_city']) ->setPostcode($params['estimate_to_zip_code']) ->setRegionId($params['estimate_to_state_code']) ->setRegion($params['estimate_to_state']) ->setCollectShippingRates(true) ->setShippingMethod($params['carrier_method']) ->setQuote($quote) ->save(); $quote->save(); $cart->save(); I imagine there's a good chance this is not the best place to save this info, but I am not quite sure. I was wondering if there is a good place to do this without overriding a whole controller to save the address on the add to cart action. Thanks so much, let me know if I need to clarify

    Read the article

  • Where should I remove a notification observer?

    - by nevan
    I set up a notification observer in my view controll init method like so: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveState) name:UIApplicationWillResignActiveNotification object:nil]; Where is the best place to call removeObserver:name:object: for this notification. I'm currently calling it in my dealloc method, but wanted to know if that might cause problems.

    Read the article

  • how to dynamically add observer methods to an Ember.js object

    - by Rick Moss
    So i am trying to dynamically add these observer methods to a Ember.js object holderStandoutCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentStandout(@get("standoutHolderChecked")) ).observes("standoutHolderChecked") holderPaddingCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentPadding(@get("holderPaddingChecked")) ).observes("holderPaddingChecked") holderMarginCheckedChanged: (-> if @get("controller.parent.isLoaded") @get("controller").toggleParentMargin(@get("holderMarginChecked")) ).observes("holderMarginChecked") I have this code so far but the item.methodToCall function is not getting called methodsToDefine = [ {checkerName: "standoutHolderChecked", methodToCall: "toggleParentStandout"}, {checkerName: "holderPaddingChecked", methodToCall: "toggleParentPadding"}, {checkerName: "holderMarginChecked", methodToCall: "toggleParentMargin"} ] add_this = { } for item in methodsToDefine add_this["#{item.checkerName}Changed"] = (-> if @get("controller.parent.isLoaded") @get("controller")[item.methodToCall](@get(item.checkerName)) ).observes(item.checkerName) App.ColumnSetupView.reopen add_this Can anyone tell me what i am doing wrong ? Is there a better way to do this ? Should i be doing this in a mixin ? If so please

    Read the article

  • how to implement this observer pattern?

    - by lethal
    Hello. I have 4 classes, that describe state diagram. Node, Edge, ComponentOfNode, ComponentOfEdge. ComponentOfEdge compounds from ComponentsOfNode. Node can have 0..n outgoing edges. Edge can have only 2 nodes. Edge should be able to offer ComponentOfNode, but only from nodes that Edge has, in form ComponentOfEdge. The user can change ComponentsOfNode. I need this change spreads to all Edge. Hw to do it? I expect the observer should be used. Can you give me example in pseudocode please?

    Read the article

  • Adding Listeners at runtime? - Java MVC

    - by Halo
    My model in my MVC pattern, generates components at runtime and gives them to the View to be displayed on the screen through update() method (you know, model is the observable and the view is the observer). But I also need to add listeners to these components, and the controller has the listener methods (because they say the MVC pattern is like this) and it's not involved in this update process. So I can't add the listeners at runtime, but only in the controller's constructor at startup. I've got an idea, that is making the controller the observer and then giving the data to the view, as well as adding the listeners. Do you think this would be OK?

    Read the article

  • Handling exceptions raised in observers

    - by sparky
    I have a Rails (2.3.5) application where there are many groups, and each Group has_many People. I have a Group edit form where users can create new people. When a new person is created, they are sent an email (the email address is user entered on the form). This is accomplished with an observer on the Person model. The problem comes when ActionMailer throws an exception - for example if the domain does not exist. Clearly that cannot be weeded out with a validation. There would seem to be 2 ways to deal with this: A begin...rescue...end block in the observer around the mailer. The problem with this is that the only way to pass any feedback to the user would be to set a global variable - as the observer is out of the MVC flow, I can't even set a flash[:error] there. A rescue_from in the Groups controller. This works fine, but has 2 problems. Firstly, there is no way to know which person threw the exception (all I can get is the 503 exception, no way to know which person caused the problem). This would be useful information to be able to pass back to the user - at the moment, there is no way for me to let them know which email address is the problem - at the moment, I just have to chuck the lot back at them, and issue an unhelpful message saying that one of them is not correct. Secondly (and to a certain extent this make the first point moot) it seems that it is necessary to call a render in the rescue_from, or it dies with a rather bizarre "can't convert Array into String" error from webbrick, with no stack trace & nothing in the log. Thus, I have to throw it back to the user when I come across the first error and have to stop processing the rest of the emails. Neither of the solutions are optimal. It would seem that the only way to get Rails to do what I want is option 1, and loathsome global variables. This would also rely on Rails being single threaded. Can anyone suggest a better solution to this problem?

    Read the article

  • How to face observable object containing an observable field

    - by iseek
    Hello, I need a hint concerning MVC and Observer-Pattern. For example a model contains the classes "Address" and "Person". The Address class contains the fields street:String, zipcode:String, location:String. Whereas the Person class contains the fields name:String, firstName:String, address:Address. My approach so far looks something like this: Both, Address and Person are observable. If one of their setters is being called, I validate whether the current value and new value differ. Only in this case an update event is fired. The event contains the source, the name of the changed field, the old and the new value. The class for the view contains text fields to display and edit the information of a person: name, firstname, street, zipcode, location. It knows the Person model and is an subscribed observer for the person. So it gets the update events from the person object. My questions concerns the address field from type Address in the person class, since an address is observable on its own. If the view gets an update event from person when a new address has been set, I can update all of the address related fields in the view. But what if a field of the address changes? Should the view also register for update events from the address? Any hints about common design approaches would be appreciated. Greetings.

    Read the article

  • Cocoa threading question.

    - by Steve918
    I would like to implement an observer pattern in Objective-C where the observer implements an interface similar to SKPaymentTransactionObserver and the observable class just extends my base observable. My observable class looks something like what is below. Notice I'm making copies of the observers before enumeration to avoid throwing an exception . I've tried adding an NSLock around add observers and notify observers, but I run into a deadlock. What would be the proper way to handle concurrency when observers are being added as notifications are being sent? @implementation Observable -(void)notifyObservers:(SEL)selector { @synchronized(self) { NSSet* observer_copy = [observers copy]; for (id observer in observer_copy) { if([observer respondsToSelector: selector]) { [observer performSelector: selector]; } } [observer_copy release]; } } -(void)notifyObservers:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 { @synchronized(self) { NSSet* observer_copy = [observers copy]; for (id observer in observer_copy) { if([observer respondsToSelector: selector]) { [observer performSelector: selector withObject: arg1 withObject: arg2]; } } [observer_copy release]; } } -(void)addObserver:(id)observer { @synchronized(self) { [observers addObject: observer]; } } -(void)removeObserver:(id)observer { @synchronized(self) { [observers removeObject: observer]; } }

    Read the article

  • How to allow one thread to mutate an array property while another thread iterates on a copy of the a

    - by Steve918
    I would like to implement an observer pattern in Objective-C where the observer implements an interface similar to SKPaymentTransactionObserver and the observable class just extends my base observable. My observable class looks something like what is below. Notice I'm making copies of the observers before enumeration to avoid throwing an exception . I've tried adding an NSLock around add observers and notify observers, but I run into a deadlock. What would be the proper way to handle concurrency when observers are being added as notifications are being sent? @implementation Observable -(void)notifyObservers:(SEL)selector { @synchronized(self) { NSSet* observer_copy = [observers copy]; for (id observer in observer_copy) { if([observer respondsToSelector: selector]) { [observer performSelector: selector]; } } [observer_copy release]; } } -(void)notifyObservers:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 { @synchronized(self) { NSSet* observer_copy = [observers copy]; for (id observer in observer_copy) { if([observer respondsToSelector: selector]) { [observer performSelector: selector withObject: arg1 withObject: arg2]; } } [observer_copy release]; } } -(void)addObserver:(id)observer { @synchronized(self) { [observers addObject: observer]; } } -(void)removeObserver:(id)observer { @synchronized(self) { [observers removeObject: observer]; } }

    Read the article

  • Seam - list all components

    - by Walter White
    Hi all, I would like to get a list of all the components so that I can further process them. Is this possible, if so, how can I do that? I don't believe I can observe all postCreate events since it is simply an exact match and not a regular expression. @Observer("org.jboss.seam.postCreate.") You can only observe those events and not * as it is put into a map where the key is a string. Any ideas? Walter

    Read the article

  • browser instant updates with ajax/jquery

    - by wcpro
    I'm trying to reverse engineer how facebook handles their notifications, where when you get a message you get instantly notified via the browser. I've fiddled with it for a little bit and realized that there is always a pending GET request "listening" if you will to some sort of update from the server. This appears to be some sort of observer pattern. I was just wondering if this pattern was documented somewhere.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >